检测客户端何时与我的服务器断开连接

Detecting when a client has disconnected from my server

我正在尝试寻找一种方法来查看连接到我的服务器的客户端何时断开连接。我的代码的大致结构是这样的,我省略了代码中不相关的部分:

public class Server {

    public static void main(String[] args) {
    ...
        try {
            ServerSocket socket = new ServerSocket(port);
            while (true) {
                // wait for connection
                Socket connection = socket.accept();
                // create client socket and start
                Clients c = new Server().new Clients(connection);
                c.start();
                System.out.printf("A client with IP %s has connected.\n",c.ip.substring(1) );
            }
        } catch (IOException exception) {
            System.out.println("Error: " + exception);
        }
    }

    class Clients extends Thread {
        ...
        public Clients(Socket socket) {         
            clientSocket = socket;
            ip=clientSocket.getRemoteSocketAddress().toString();
            try {
                client_in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                client_out = new PrintWriter(clientSocket.getOutputStream(), true);
            } catch (IOException e) {
                //error
            }
        }
        public void run() {
            ...
            try {
                while (true) {
                    while ((message = client_in.readLine()) != null) {
                    ...
                    }
                }
            } catch (IOException exception) {
                System.out.printf("Client with IP %s has disconnected.\n" , ip.substring(1));
            }
        }
    }
}

基本上我现在正在尝试的是通过 运行() 中的 catch 语句检测断开连接,但问题是它在我终止我的服务器之前不会显示消息。

我也曾尝试将打印语句放在 while(true) 循环之后,但我的 IDE 告诉我代码无法访问。

有没有办法让我的 "Client with IP %s has disconnected." 在客户端连接断开后立即显示?我应该检查什么以及在哪里检查?

what I'm trying to do is detecting the disconnection through the catch statement.

嗡嗡声。 readLine() 不会在流结束时抛出异常。它 returns 无效。您在此处捕获的任何异常都是 错误,应按此报告。

while (true) {
    while ((message = client_in.readLine()) != null) {
        ...
}

问题就在这里。您 正在 检测对等方何时断开连接: readLine() returns null 并终止内部循环。但是,您毫无意义地将正确的内部读取循环包含在外部 while (true) 循环中,根据定义,该循环永远不会退出。

删除外循环。