使用资源在 Try-Catch 中打印到控制台

问题描述 投票:0回答:1

我希望服务器在玩家通过套接字连接时打印到控制台。但是,我的 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();
        }
java try-catch
1个回答
0
投票

我使用了 Closeable 类的构造函数:

import java.io.Closeable;
class CloseableLogger implements Closeable {
    CloseableLogger(String message) {
        System.out.println(message);
    }

    @Override
    public void close() throws IOException {
        // Do nothing
    }
}

用法:

try (
    CloseableLogger c1 = new CloseableLogger("Before creating Buffered Reader");
    BufferedReader in = new BufferedReader(
            new InputStreamReader(clientSocket.getInputStream()));
    CloseableLogger c2 = new CloseableLogger("After creating Buffered Reader");
) {
    // Code
}
© www.soinside.com 2019 - 2024. All rights reserved.