Improved the handling of closing the socket.