'Close the socket cleanly'

def _cleanup_socket(self):

    if self.socket:
        try:
            self.socket.shutdown(socket.SHUT_RDWR)
        except _SOCKET_ERROR:
            pass
        self.socket.close()
        self.socket = None
