简体   繁体   English

java socket服务器,客户端检测服务器已经死亡

[英]java socket server, client detect server has died

If I kill the Socket Server process, my Socket client process does not receive any errors, it continues to loop forever on the following code: 如果我终止了Socket Server进程,我的Socket客户端进程没有收到任何错误,它将继续循环使用以下代码:

public void run() {
    while(readData) {
      String inputLine = null;
      try {
        while((inputLine = m_inputStream.readLine()) != null) {
          //do stuff
        }
      } catch (IOException e) {
         readData = false;
     }
  }
}

How can I detect that the socket server is gone and terminate the loop? 如何检测套接字服务器已经消失并终止循环?

Terminate the outer loop when the call to readLine() returns null . 当对readLine()的调用返回null时终止外部循环。

No exception is thrown when the server closes the connection normally. 服务器正常关闭连接时不会抛出异常。 The stream should return null to signal the end of data. 流应返回null以表示数据结束。

This can be done with a loop like this: 这可以通过这样的循环完成:

public void run() {
  try {
    while (true) {
      String line = input.readLine();
      if (line == null)
        break;
      /* Process line. */
      ...
    }
  } catch (IOException ex) {
    /* Handle the exception as desired. */
    ex.printStackTrace();
  }
}

Whilst the answer from erickson is correct, have you tried setting the socket read time-out properties ? 虽然erickson的答案是正确的,您是否尝试过设置套接字读取超时属性 (eg sun.net.client.defaultReadTimeout ). (例如sun.net.client.defaultReadTimeout )。 If it is possible that the server may take a long time responding, then this might be less useful as a solution to your problem but is a good idea nevertheless in many scenarios. 如果服务器可能需要很长时间的响应,那么这可能不太有用作为您的问题的解决方案,但在许多情况下仍然是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM