Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between closing Input/OutputStream and closing Socket directly?

Tags:

I just wondering what java does when we call close on the inputStream and outStream associated with a socket. What is the difference from the close call on the socket, i.e Socket.close().

if we just close the io stream on the socket, but not close the socket, can we reopen the io stream on the socket again?

Thanks in advance!

like image 263
Alfred Avatar asked Aug 06 '10 22:08

Alfred


People also ask

What is the difference between InputStream and OutputStream?

The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination.

Does closing stream close socket?

Yes, closing the input stream closes the socket.

Do input streams need to be closed?

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.

What is end of stream?

You never got a null because the peer never closed the connection. That's what 'end of stream' means. It doesn't mean 'no more data for the time being'.


2 Answers

From the java api documentation for Socket:

public void close() throws IOException Closes this socket. Any thread currently blocked in an I/O operation upon this socket will throw a SocketException.

Once a socket has been closed, it is not available for further networking use (i.e. can't be reconnected or rebound). A new socket needs to be created.

Closing this socket will also close the socket's InputStream and OutputStream.

If this socket has an associated channel then the channel is closed as well.

Closing the InputStream of the Socket will lead to the closing of the Socket. The same goes for closing the OutputStream of the Socket.

From the java api documentation for Socket#getInputStream()

Closing the returned InputStream will close the associated socket.

Check the API documentation, it is there for a reason.

like image 159
Jes Avatar answered Jan 02 '23 17:01

Jes


You should close the outermost output stream you have created from the socket. That will flush it. Closing either the socket or the input stream doesn't do that so it isn't adequate. Having closed that output stream you don't need to do anything else.

like image 32
user207421 Avatar answered Jan 02 '23 19:01

user207421