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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3956163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 04:07:43  来源:igfitidea点击:

Does closing the inputstream of a socket also close the socket connection?

javaapisockets

提问by dolaameng

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. Does that mean that closing the inputstream of a socket also closes the socket itself?

在上面的代码中,在我关闭 InputStream fromSocket 后,似乎套接字连接不再可用——客户端不会收到“套接字连接仍然可用”的消息。这是否意味着关闭套接字的输入流也会关闭套接字本身?

回答by Michael Goldshteyn

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();