【问题标题】:Socket closing not throwing IOException套接字关闭不抛出 IOException
【发布时间】:2011-09-21 22:45:02
【问题描述】:

我正在用 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。

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

【问题讨论】:

  • 考虑使用连接超时并注意 SocketExceptions。
  • 连接超时是个好主意,我认为SocketException是IOException的子类。

标签: java sockets client-server


【解决方案1】:

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

【讨论】:

  • 我们通常从远程套接字读取如下: String msg = null; while ((msg = s.readLine()) != null) { //在 msg 上做一些事情 read ... } //套接字已从远程端关闭。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-27
  • 2017-02-17
  • 2011-09-04
  • 2016-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多