2013-05-05 164 views
1

我正在做一個客戶端到服務器的登錄通信。Java SocketException損壞的管道

我遇到了一個java.net.SocketException:在服務器端壞了Pipe。並且我已將 問題縮小到客戶端的一條單線。如果我爲這一行移動一個位置,代碼將起作用 。請參閱以下代碼。

客戶端:

Socket socket = new Socket(Const.destIp, 12101); 
    ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream()); 
    out.writeObject(this.message);    
    out.close();//Line that cause problem 
    ObjectInputStream in = new ObjectInputStream(socket.getInputStream()); 
    ServerToClientLogin msg = (ServerToClientLogin) in.readObject(); 
    //out.close();//move it to here, problem solved 
    in.close(); 
    socket.close(); 

服務器端:

while (true) { 
    socket = _serverSocket.accept(); 
    in = new ObjectInputStream(socket.getInputStream()); 
    msg = (ClientToServerLogin) in.readObject(); 

    ServerToClientLogin msgToSend = null; 
    out = new ObjectOutputStream(socket.getOutputStream()); 
    msgToSend = handleLoginRequest(msg); 
    if(msgToSend != null) out.writeObject(msgToSend); 

    try { in.close(); } catch (IOException e) {e.printStackTrace();} 
    try { out.close();} catch (IOException e) {e.printStackTrace(); } 
    try { socket.close();} catch (IOException e) {e.printStackTrace();} 

} 

由於一個對象的讀寫是阻塞調用,我不知道爲什麼關閉它前面會區分這樣的問題。

回答

1

out.close();:關閉此(out)輸出流並釋放與此流關聯的所有系統資源。

查看API here

+0

out是ObjectOutputStream類型,調用out.close()會關閉它的套接字? – SDEZero 2013-05-05 04:13:42

+0

關閉此輸出流並釋放與此流關聯的所有系統資源,這在API – PbxMan 2013-05-05 04:14:56

+0

@PbxMan中添加您對答案的說法,它會使其更清晰。 – acdcjunior 2013-05-05 04:18:58

相關問題