Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

sockets

api

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?

like image 717
dolaameng Avatar asked Oct 18 '10 01:10

dolaameng


People also ask

Does closing stream close socket?

The Close method frees both unmanaged and managed resources associated with the NetworkStream. If the NetworkStream owns the underlying Socket, it is closed as well. If a NetworkStream was associated with a TcpClient, the Close method will close the TCP connection, but not dispose of the associated TcpClient.

How do you close a socket connection?

close() call shuts down the socket associated with the socket descriptor socket, and frees resources allocated to the socket. If socket refers to an open TCP connection, the connection is closed. If a stream socket is closed when there is input data queued, the TCP connection is reset rather than being cleanly closed.

What happens if you don't close InputStream?

The operating system will only allow a single process to open a certain number of files, and if you don't close your input streams, it might forbid the JVM from opening any more.

Do I need to close InputStream?

You do need to close the input Stream, because the stream returned by the method you mention is actually FileInputStream or some other subclass of InputStream that holds a handle for a file. If you do not close this stream you have resource leakage.


1 Answers

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();  
like image 63
Michael Goldshteyn Avatar answered Sep 22 '22 14:09

Michael Goldshteyn