Do I have to explicitly close the socket input and output streams before I close a socket?

Tim Rohaly

While closing the socket will close the underlying socket input and output streams, programs typically wrap these streams in other streams. It is important to flush and close these other streams, preferably in a finally block, before closing the socket. This will help to ensure that all application data is properly sent or received and that your program isn't unnecesarily holding on to file descriptors that it no longer needs. An example of this follows:

Socket socket;
BufferedOutputStream out;
try {
    socket = new Socket(host, port);
    out = new BufferedOutputStream(socket.getOutputStream());
    // write to the socket using the"out" stream
catch (IOException e) {
    // handle errors
finally {
    try {
    catch (IOException e) { /*ignore*/ }
Although the structure of the finally block is a little awkward in this case, it does ensure that the streams and the socket are properly closed down, whether or not an exception occurred.
0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.