2012-12-01 141 views
2

我有經由PrintWriter的(out.write(字符串str))發送文本數據的套接字程序,在另一側的BufferedReader(in.readLine())正在接收此。中斷插座連接

我想用某種「超時」,如果一個客戶端斷開連接保護我的計劃,但我測試了它和工作,當客戶端將被關閉,服務器仍然發送數據並沒有中斷,也沒有在套接字關閉。

同一客戶端,我想打破連接並顯示例如信息「服務器不工作」。 我該如何處理?

// Server 
out = new PrintWriter(sock.getOutputStream()); 
while(true) { 
    this.out.write("Hello"); 
    this.out.flush(); 
} 

// Client 
in = new BufferedReader(new InputStreamReader(sock.getInputStream())); 
while (true) { 
    in.readLine(); 
} 

回答

2

我認爲你的問題是PrintWriter。見its documentation

方法在這個類不會拋出I/O異常,儘管它的一些 構造的可能。客戶端可以查詢到任何錯誤是否有() 通過調用checkError發生的。

改爲使用BufferedWriter

注意java.util.Scanner中有同樣的問題(如果你使用的是它在服務器端)

1

我只是檢查和PrintWriter.checkError()方法幫助我與我的問題。當客戶端斷開連接時,方法返回true。至於說描述:當對方關閉連接Flushes the stream if it's not closed and checks its error state.

// Server 
this.out = new PrintWriter(sock.getOutputStream()); 
while (true) { 
    this.out.write("Hello"); 
    this.out.flush(); 
    if(this.out.checkError()){ 
     //... 
    } 
} 
+0

的readLine()返回null。 – EJP