Discuss / Java / 服务端无法打印client disconnected

服务端无法打印client disconnected

Topic source

在服务端的代码中:

for (;;) {
            String s = reader.readLine();
            if (s.equals("bye")) {
                writer.write("bye\n");
                writer.flush();
                break;
            }
            writer.write("ok: " + s + "\n");
            writer.flush();
        }

当用户的发送的消息为"bye"时,有break语句,所以:

public void run() {
        try (InputStream input = this.sock.getInputStream()) {
            try (OutputStream output = this.sock.getOutputStream()) {
                handle(input, output);
            }
        } catch (Exception e) {
            try {
                this.sock.close();
            } catch (IOException ioe) {
            }
            System.out.println("client disconnected.");
        }
    }

在这里调用的handle函数就会正常退出,不会抛异常,就不会有异常被捕捉到,就不会调用catch里面的语句,也就不会执行:

this.sock.close()

System.out.println("client disconnected.");

The__Wolf

#2 Created at ... [Delete] [Delete and Lock User]

那如何才能print这条信息,是客户端异常中断吗?

还有就是服务器端只能手动关闭了啊


  • 1

Reply