Search code examples
javasocketstcpserversocket

Closing Sockets Procedure


In a TCP connection between sockets. What is the correct procedure to closing/shutting down the connection?

I have outputstreams, bufferedreaders and printwriters. Will closing the socket close all of them? Should they be closeds at both ends?(server and client)


Solution

    • You should close the outermost stream or writer you have wrapped around the socket output stream. That way it will get flushed if it is buffered.
    • Closing either the input or output stream or the socket closes everything else.
    • 'Should they be closed at both ends?' doesn't really make sense. Sockets don't have two ends: connections do. The connection must be closed at both ends, but both ends have a socket, and all sockets must be closed.