• Post Reply Bookmark Topic Watch Topic
  • New Topic

Closing I/O Streams closes a socket

 
Hazem Hamam
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello everyone,

Suppose I have created a socket and a ServerSocket, established the link between them and created input and output streams like this:
Input = new ObjectInputStream(comSocket.getInputStream());
output = new ObjectOutputStream(comSocket.getOutputStream());

I am done reading or writing to the socket now and I decided to close the streams so I only called:
input.close();
output.close();

I did not call Socket.close() on either side.

Now I decided I need to read or write again, when I try to create new I/O streams over the socket I get an exception: Socket is Closed.

What I think is that calling input.close() or output.close() closes the socket as well.

1. Is my assumption correct?
2. Is there a way to avoid closing the socket when closing streams on it?
3. Is it better to keep input and output unclosed and just pass them to other methods or classes for use until I decide I should close the socket?

Thanks
 
Edwin Dalorzo
Ranch Hand
Posts: 961
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The InputStream and OutputStream returned by the Socket class are implemented on an pair of classes named SocketInputStream and SocketOuputStream.

These classes have package accessibility, that's why you cannot see their definition in the javadoc API.

However, if you take a look at the source code (which comes withe the JDK), you will see that whenever you close one of these streams, the close() method checks if the Socket is not closed and then close it.

Hence, your assertion is true, whenever you close one of these streams, the Socket is closed.

Do not close your streams until you are done with your Socket.

At the end, just close the Socket and all resources associated with it will be released as well.

Best regards,
Edwin Dalorzo
[ May 06, 2006: Message edited by: Edwin Dalorzo ]
 
Hazem Hamam
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks alot,

I will try to work it out without closing the streams.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!