当播放器通过套接字连接时,我希望服务器打印到控制台。但是,我的IDE拒绝让我尝试在try-catch中使用System.out.println(“ P1 Connected”)和资源。
我调查了一下问题,发现带有资源的try-catch内部的调用必须实现closeable。虽然这样做确实是有道理的,但它们阻止了通话,我似乎无法找到另一种方法来确保在播放器连接后立即打印。
我可以将其分解为两个带资源的try-catch,但是我丢失了对P1和P2客户端套接字的引用。据我所知,我对这些套接字的所有操作都必须在try-catch之后的{}内进行,因为否则它们将被关闭,并且由于范围的原因,它们将无法再访问。
//Setup the server socket for client one
try (
ServerSocket serverSocket = new ServerSocket(Integer.parseInt(args[1]));
Socket clientOne = serverSocket.accept();
BufferedReader clientOneIn = new BufferedReader(new InputStreamReader(clientOne.getInputStream()));
PrintWriter clientOneOut = new PrintWriter(clientOne.getOutputStream(), true);
System.out.println("Player one connected!");
Socket clientTwo = serverSocket.accept();
BufferedReader clientTwoIn = new BufferedReader(new InputStreamReader(clientTwo.getInputStream()));
PrintWriter clientTwoOut = new PrintWriter(clientTwo.getOutputStream(), true);
) {
} catch (IOException e) {
e.printStackTrace();
}