Reputation: 1437
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?
Upvotes: 31
Views: 24695
Reputation: 74340
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();
Upvotes: 43