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

时间:2021-11-11 07:39:01

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后,似乎套接字连接不再可用 - 客户端不会收到“仍然是套接字连接”消息。这是否意味着关闭套接字的输入流也会关闭套接字本身?

1 个解决方案

#1


35  

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

#1


35  

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