tags:

views:

49

answers:

1

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?

+1  A: 

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(); 
Michael Goldshteyn
So does it close the socket connection when I close the InputStream?
dolaameng
No, it does a one way shutdown, closing the input half of the socket (so that you cannot receive any more data), but still letting you send your message on the output half, which I thought is what you were asking. When you ultimately call close() on the socket, the output side gets closed as well.
Michael Goldshteyn
Yes, closing the input stream closes the socket. Ditto the output stream. So of course what you should close is always the output stream, so It gets flushed.
EJP