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

时间:2018-02-02 22:24:40

标签: java sockets connection

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

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));
            }
        }
    }
}

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

我还尝试在while(true)循环之后放置我的print语句,但我的IDE告诉我代码无法访问。

有没有办法让我的"客户端与IP%s断开连接。"一旦断开客户端连接就显示?我应该检查什么和在哪里?

1 个答案:

答案 0 :(得分:0)

  

我要做的是通过catch语句检测断开连接。

Bzzt。 readLine()不会在流结束时抛出异常。它返回null。您在此处捕获的任何异常都是错误,应该如此报告。

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

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

移除外环。