简体   繁体   中英

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

In 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?

Yes, closing the input stream closes the socket. You need to use the shutdownInput method on socket, to close just the input stream :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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