套接字关闭不抛出IOException

时间:2011-09-21 22:45:03

标签: java sockets client-server

我正在用Java编写一个基本的服务器 - 客户端程序,我正在尝试处理客户端意外终止的情况。

public void run() {
    while(alive) {
        try {
            // socketIn is a BufferedReader wrapped around the socket's InputStream.
            String input = socketIn.readLine();
            if(input == null)
                continue;
            String response = processInput(input);
            // socketOut is a PrintWriter wrapped around the socket's OutputStream.
            if(response != null) {
                socketOut.println(response);
                socketOut.flush();
            }
        } catch(IOException e) {
            System.out.println("TRACE 1");
            alive = false;
        }
    }
    System.out.println("TRACE 2");
}

但是当我杀死客户端时,循环继续运行,并且都没有打印出TRACE。我假设当套接字从另一端关闭并且我试图从它读取时,它将抛出IOException。

这是一个不好的假设吗?我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:4)

readLine()将在流末尾返回null,这是远程端正常关闭连接时发生的情况。你正试图continue在这种情况下,这将永远循环。如果连接异常中断,将抛出IOException

相关问题