![](/img/trans.png)
[英]Does closing the BufferedReader/PrintWriter close the socket connection?
[英]Does closing the inputstream of a socket also close the socket connection?
在Java API中,
Socket socket = serverSocket.accept();
BufferedReader fromSocket = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter toSocket = new PrintWriter(socket.getOutputStream());
//do sth with fromSocket ... and close it
fromSocket.close();
//then write to socket again
toSocket.print("is socket connection still available?\r\n");
//close socket
socket.close();
在上面的代码中,在我关闭InputStream fromSocket后,似乎套接字连接不再可用 - 客户端不会收到“仍然是套接字连接”消息。 这是否意味着关闭套接字的输入流也会关闭套接字本身?
是的,关闭输入流会关闭套接字。 您需要在套接字上使用shutdownInput方法,以仅关闭输入流 :
//do sth with fromSocket ... and close it
socket.shutdownInput();
然后,您仍然可以发送到输出套接字
//then write to socket again
toSocket.print("is socket connection still available?\r\n");
//close socket
socket.close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.