[英]java socket server, client detect server has died
如果我终止了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;
}
}
}
如何检测套接字服务器已经消失并终止循环?
当对readLine()
的调用返回null
时终止外部循环。
服务器正常关闭连接时不会抛出异常。 流应返回null
以表示数据结束。
这可以通过这样的循环完成:
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();
}
}
虽然erickson的答案是正确的,您是否尝试过设置套接字读取超时属性 ? (例如sun.net.client.defaultReadTimeout
)。 如果服务器可能需要很长时间的响应,那么这可能不太有用作为您的问题的解决方案,但在许多情况下仍然是一个好主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.