简体   繁体   English

关闭套接字的输入流是否也会关闭套接字连接?

[英]Does closing the inputstream of a socket also close the socket connection?

In Java API, 在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();

In the above code, after I close the InputStream fromSocket, it seems that the socket connection is not available anymore--the client wont receive the "is socket connection still available" message. 在上面的代码中,在我关闭InputStream fromSocket后,似乎套接字连接不再可用 - 客户端不会收到“仍然是套接字连接”消息。 Does that mean that closing the inputstream of a socket also closes the socket itself? 这是否意味着关闭套接字的输入流也会关闭套接字本身?

Yes, closing the input stream closes the socket. 是的,关闭输入流会关闭套接字。 You need to use the shutdownInput method on socket, to close just the input stream : 您需要在套接字上使用shutdownInput方法,以仅关闭输入流

//do sth with fromSocket ... and close it 
socket.shutdownInput(); 

Then, you can still send to the output socket 然后,您仍然可以发送到输出套接字

//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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM