我正在寫一個基本的服務器客戶端程序在Java中,我試圖處理客戶端意外終止的情況。套接字關閉不拋出IOException
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。 – Zaki
連接超時是一個好主意,我認爲SocketException是IOException的一個子類。 – DanielGibbs