我正在做一个客户端来服务器登录。
我遇到了一个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();}
}
由于readObject和writeObject都是阻塞调用,我不知道为什么之前关闭它会导致这样的问题。