【发布时间】: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