Python socket.error() Examples

The following are 30 code examples for showing how to use socket.error(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module socket , or try the search function .

Example 1
Project: RF-Monitor   Author: EarToEarOak   File: server.py    License: GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, eventHandler):
        threading.Thread.__init__(self)
        self.name = 'Server'
        self.daemon = True
        self._eventHandler = eventHandler

        self._client = None
        self._server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        try:
            self._server.bind(('', PORT))
            self._server.listen(5)
        except socket.error:
            event = Event(Events.SCAN_ERROR, msg='Could not start server')
            post_event(eventHandler, event)
            return

        self._cancel = False
        self.start() 
Example 2
Project: RF-Monitor   Author: EarToEarOak   File: server.py    License: GNU General Public License v2.0 6 votes vote down vote up
def run(self):
        while not self._cancel:
            if self._client is None:
                endpoints = [self._server]
            else:
                endpoints = [self._server, self._client]

            read, _write, error = select.select(endpoints, [], [], 0.5)

            for sock in read:
                if sock is self._server:
                    try:
                        client, _addr = self._server.accept()
                        if self._client is not None:
                            self._client.close()
                        self._client = client
                    except socket.error:
                        self._client = None

            for sock in error:
                if sock is self._client:
                    self._client = None
                sock.close() 
Example 3
Project: cherrypy   Author: cherrypy   File: test_conn.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_Content_Length_in(self):
        # Try a non-chunked request where Content-Length exceeds
        # server.max_request_body_size. Assert error before body send.
        self.persistent = True
        conn = self.HTTP_CONN
        conn.putrequest('POST', '/upload', skip_host=True)
        conn.putheader('Host', self.HOST)
        conn.putheader('Content-Type', 'text/plain')
        conn.putheader('Content-Length', '9999')
        conn.endheaders()
        response = conn.getresponse()
        self.status, self.headers, self.body = webtest.shb(response)
        self.assertStatus(413)
        self.assertBody('The entity sent with the request exceeds '
                        'the maximum allowed bytes.')
        conn.close() 
Example 4
Project: cherrypy   Author: cherrypy   File: test_http.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_http_over_https(self):
        if self.scheme != 'https':
            return self.skip('skipped (not running HTTPS)... ')

        # Try connecting without SSL.
        conn = HTTPConnection('%s:%s' % (self.interface(), self.PORT))
        conn.putrequest('GET', '/', skip_host=True)
        conn.putheader('Host', self.HOST)
        conn.endheaders()
        response = conn.response_class(conn.sock, method='GET')
        try:
            response.begin()
            self.assertEqual(response.status, 400)
            self.body = response.read()
            self.assertBody('The client sent a plain HTTP request, but this '
                            'server only speaks HTTPS on this port.')
        except socket.error:
            e = sys.exc_info()[1]
            # "Connection reset by peer" is also acceptable.
            if e.errno != errno.ECONNRESET:
                raise 
Example 5
Project: cherrypy   Author: cherrypy   File: test_http.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_garbage_in(self):
        # Connect without SSL regardless of server.scheme
        c = HTTPConnection('%s:%s' % (self.interface(), self.PORT))
        c._output(b'gjkgjklsgjklsgjkljklsg')
        c._send_output()
        response = c.response_class(c.sock, method='GET')
        try:
            response.begin()
            self.assertEqual(response.status, 400)
            self.assertEqual(response.fp.read(22),
                             b'Malformed Request-Line')
            c.close()
        except socket.error:
            e = sys.exc_info()[1]
            # "Connection reset by peer" is also acceptable.
            if e.errno != errno.ECONNRESET:
                raise 
Example 6
Project: iSDX   Author: sdn-ixp   File: policy_loader.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, address, port, key, logger, sname):
        self.address = address
        self.port = int(port)
        self.key = key
        self.logger = logger
        self.serverName = sname

        while True: # keep going until we break out inside the loop
            try:
                self.logger.debug('Attempting to connect to '+self.serverName+' server at '+str(self.address)+' port '+str(self.port))
                self.conn = Client((self.address, self.port))
                self.logger.debug('Connect to '+self.serverName+' successful.')
                break
            except SocketError as serr:
                if serr.errno == errno.ECONNREFUSED:
                    self.logger.debug('Connect to '+self.serverName+' failed because connection was refused (the server is down). Trying again.')
                else:
                    # Not a recognized error. Treat as fatal.
                    self.logger.debug('Connect to '+self.serverName+' gave socket error '+str(serr.errno))
                    raise serr
            except:
                self.logger.exception('Connect to '+self.serverName+' threw unknown exception')
                raise 
Example 7
Project: iSDX   Author: sdn-ixp   File: lib.py    License: Apache License 2.0 6 votes vote down vote up
def send(self, msg):
        # TODO: Busy wait will do for initial startup but for dealing with server down in the middle of things
        # TODO: then busy wait is probably inappropriate.
        while True: # keep going until we break out inside the loop
            try:
                self.logger.debug('Attempting to connect to '+self.serverName+' server at '+str(self.address)+' port '+str(self.port))
                conn = Client((self.address, self.port))
                self.logger.debug('Connect to '+self.serverName+' successful.')
                break
            except SocketError as serr:
                if serr.errno == errno.ECONNREFUSED:
                    self.logger.debug('Connect to '+self.serverName+' failed because connection was refused (the server is down). Trying again.')
                else:
                    # Not a recognized error. Treat as fatal.
                    self.logger.debug('Connect to '+self.serverName+' gave socket error '+str(serr.errno))
                    raise serr
            except:
                self.logger.exception('Connect to '+self.serverName+' threw unknown exception')
                raise

        conn.send(msg)

        conn.close() 
Example 8
Project: iSDX   Author: sdn-ixp   File: lib.py    License: Apache License 2.0 6 votes vote down vote up
def send(self, msg):
        # TODO: Busy wait will do for initial startup but for dealing with server down in the middle of things
        # TODO: then busy wait is probably inappropriate.
        while True: # keep going until we break out inside the loop
            try:
                self.logger.debug('Attempting to connect to '+self.serverName+' server at '+str(self.address)+' port '+str(self.port))
                conn = hub.connect((self.address, self.port))
                self.logger.debug('Connect to '+self.serverName+' successful.')
                break
            except SocketError as serr:
                if serr.errno == errno.ECONNREFUSED:
                    self.logger.debug('Connect to '+self.serverName+' failed because connection was refused (the server is down). Trying again.')
                else:
                    # Not a recognized error. Treat as fatal.
                    self.logger.debug('Connect to '+self.serverName+' gave socket error '+str(serr.errno))
                    raise serr
            except:
                self.logger.exception('Connect to '+self.serverName+' threw unknown exception')
                raise

        conn.sendall(msg)

        conn.close() 
Example 9
Project: iSDX   Author: sdn-ixp   File: tnode.py    License: Apache License 2.0 6 votes vote down vote up
def create_command_listener (baddr, port):
    try:
        if port is None:
            try:
                if os.path.exists(baddr):
                    os.unlink(baddr)
            except OSError:
                print 'could not remove old unix socket ' + baddr
                return
            s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) # @UndefinedVariable
            s.bind(baddr)
        else:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.bind((baddr, int(port)))
    except socket.error , msg:
        print 'Bind failed on command interface ' + baddr + ' port ' + str(port) + ' Error Code : ' + str(msg[0]) + ' Message ' + msg[1] + '\n'
        return 
Example 10
Project: L.E.S.M.A   Author: NatanaelAntonioli   File: L.E.S.M.A. - Fabrica de Noobs Speedtest.py    License: Apache License 2.0 6 votes vote down vote up
def validate_optional_args(args):
	"""Check if an argument was provided that depends on a module that may
	not be part of the Python standard library.

	If such an argument is supplied, and the module does not exist, exit
	with an error stating which module is missing.
	"""
	optional_args = {
		'json': ('json/simplejson python module', json),
		'secure': ('SSL support', HTTPSConnection),
	}

	for arg, info in optional_args.items():
		if getattr(args, arg, False) and info[1] is None:
			raise SystemExit('%s is not installed. --%s is '
							 'unavailable' % (info[0], arg)) 
Example 11
Project: XFLTReaT   Author: earthquake   File: TCP_generic.py    License: MIT License 6 votes vote down vote up
def send(self, channel_type, message, additional_data):
		if channel_type == common.CONTROL_CHANNEL_BYTE:
			transformed_message = self.transform(self.encryption, common.CONTROL_CHANNEL_BYTE+message, 1)
		else:
			transformed_message = self.transform(self.encryption, common.DATA_CHANNEL_BYTE+message, 1)

		common.internal_print("{0} sent: {1}".format(self.module_short, len(transformed_message)), 0, self.verbosity, common.DEBUG)

		# WORKAROUND?!
		# Windows: It looks like when the buffer fills up the OS does not do
		# congestion control, instead throws and exception/returns with
		# WSAEWOULDBLOCK which means that we need to try it again later.
		# So we sleep 100ms and hope that the buffer has more space for us.
		# If it does then it sends the data, otherwise tries it in an infinite
		# loop...
		while True:
			try:
				return self.comms_socket.send(struct.pack(">H", len(transformed_message))+transformed_message)
			except socket.error as se:
				if se.args[0] == 10035: # WSAEWOULDBLOCK
					time.sleep(0.1)
					pass
				else:
					raise 
Example 12
Project: XFLTReaT   Author: earthquake   File: TCP_generic.py    License: MIT License 6 votes vote down vote up
def check(self):
		try:
			common.internal_print("Checking module on server: {0}".format(self.get_module_name()))

			server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			server_socket.settimeout(3)
			server_socket.connect((self.config.get("Global", "remoteserverip"), int(self.config.get(self.get_module_configname(), "serverport"))))
			client_fake_thread = TCP_generic_thread(0, 0, None, None, server_socket, None, self.authentication, self.encryption_module, self.verbosity, self.config, self.get_module_name())
			client_fake_thread.do_check()
			client_fake_thread.communication(True)

			self.cleanup(server_socket)

		except socket.timeout:
			common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
			self.cleanup(server_socket)
		except socket.error as exception:
			if exception.args[0] == 111:
				common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
			else:
				common.internal_print("Connection error: {0}".format(self.get_module_name()), -1)
			self.cleanup(server_socket)

		return 
Example 13
Project: XFLTReaT   Author: earthquake   File: SCTP_generic.py    License: MIT License 6 votes vote down vote up
def check(self):
		try:
			common.internal_print("Checking module on server: {0}".format(self.get_module_name()))

			server_socket = self.sctp.sctpsocket_tcp(socket.AF_INET)
			server_socket.settimeout(3)
			server_socket.connect((self.config.get("Global", "remoteserverip"), int(self.config.get(self.get_module_configname(), "serverport"))))
			client_fake_thread = SCTP_generic_thread(0, 0, None, None, server_socket, None, self.authentication, self.encryption_module, self.verbosity, self.config, self.get_module_name())
			client_fake_thread.do_check()
			client_fake_thread.communication(True)

			self.cleanup(server_socket)

		except socket.timeout:
			common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
			self.cleanup(server_socket)
		except socket.error as exception:
			if exception.args[0] == 111:
				common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
			else:
				common.internal_print("Connection error: {0}".format(self.get_module_name()), -1)
			self.cleanup(server_socket)

		return 
Example 14
Project: XFLTReaT   Author: earthquake   File: WebSocket.py    License: MIT License 6 votes vote down vote up
def communication_initialization(self):
		try:
		
			common.internal_print("Waiting for upgrade request", 0, self.verbosity, common.DEBUG)
			response = self.comms_socket.recv(4096)

			if len(response) == 0:
				common.internal_print("Connection was dropped", 0, self.verbosity, common.DEBUG)
				self.cleanup()
				sys.exit(-1)
			handshake_key = self.WebSocket_proto.get_handshake_init(response)
			if handshake_key == None:
				common.internal_print("No WebSocket-Key in request", -1, self.verbosity, common.DEBUG)
				self.cleanup()
				sys.exit(-1)

			handshake = self.WebSocket_proto.calculate_handshake(handshake_key)
			response = self.WebSocket_proto.switching_protocol(handshake)
			self.comms_socket.send(response)
		except:
			common.internal_print("Socket error", -1, self.verbosity, common.DEBUG)
			self.cleanup()
			sys.exit(-1)

		return 
Example 15
Project: XFLTReaT   Author: earthquake   File: UDP_generic.py    License: MIT License 6 votes vote down vote up
def connect(self):
		try:
			common.internal_print("Starting client: {0}".format(self.get_module_name()))
			server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
			self.server_tuple = (self.config.get("Global", "remoteserverip"), int(self.config.get(self.get_module_configname(), "serverport")))
			self.comms_socket = server_socket
			self.serverorclient = 0
			self.authenticated = False

			self.do_hello()
			self.communication(False)

		except KeyboardInterrupt:
			self.do_logoff()
			self.cleanup()
			raise
		except socket.error:
			self.cleanup()
			raise

		self.cleanup()

		return 
Example 16
Project: XFLTReaT   Author: earthquake   File: UDP_generic.py    License: MIT License 6 votes vote down vote up
def check(self):
		try:
			common.internal_print("Checking module on server: {0}".format(self.get_module_name()))

			server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
			self.server_tuple = (self.config.get("Global", "remoteserverip"), int(self.config.get(self.get_module_configname(), "serverport")))
			self.comms_socket = server_socket
			self.serverorclient = 0
			self.authenticated = False

			self.do_check()
			self.communication(True)

		except KeyboardInterrupt:
			self.cleanup()
			raise
		except socket.timeout:
			common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
		except socket.error:
			self.cleanup()
			raise

		self.cleanup()

		return 
Example 17
Project: macops   Author: google   File: gmacpyutil.py    License: Apache License 2.0 6 votes vote down vote up
def ReleasePowerAssertion(io_lib, assertion_id):
  """Releases a power assertion.

  Assertions are released with IOPMAssertionRelease, however if they are not,
  assertions are automatically released when the process exits, dies or
  crashes, i.e. a crashed process will not prevent idle sleep indefinitely.

  Args:
    io_lib: IOKit library from ConfigureIOKit()
    assertion_id: c_uint, assertion identification number from
        CreatePowerAssertion()

  Returns:
    0 if successful, stderr otherwise.
  """
  try:
    return io_lib.IOPMAssertionRelease(assertion_id)
  except AttributeError:
    return 'IOKit library returned an error.' 
Example 18
Project: pyfirebase   Author: afropolymath   File: firebase.py    License: MIT License 6 votes vote down vote up
def run(self):
        try:
            self.sse = ClosableSSEClient(self.url)
            for msg in self.sse:
                event = msg.event
                if event is not None and event in ('put', 'patch'):
                    response = json.loads(msg.data)
                    if response is not None:
                        # Default to CHILD_CHANGED event
                        occurred_event = FirebaseEvents.CHILD_CHANGED
                        if response['data'] is None:
                            occurred_event = FirebaseEvents.CHILD_DELETED

                        # Get the event I'm trying to listen to
                        ev = FirebaseEvents.id(self.event_name)
                        if occurred_event == ev or ev == FirebaseEvents.CHILD_CHANGED:
                            self.callback(event, response)
        except socket.error:
            pass 
Example 19
Project: EvilOSX   Author: cys3c   File: Server.py    License: GNU General Public License v3.0 6 votes vote down vote up
def send_command(connection, message):
    try:
        connection.sendall(message)

        response = connection.recv(4096)
        global current_client_id

        if not response:  # Empty
            current_client_id = None
            connections.remove(connection)

            status_messages.append(MESSAGE_ATTENTION + "Client disconnected!")
            return None
        else:
            return response
    except socket.error:
        current_client_id = None
        connections.remove(connection)

        status_messages.append(MESSAGE_ATTENTION + "Client disconnected!")
        return None 
Example 20
Project: glazier   Author: google   File: download.py    License: Apache License 2.0 6 votes vote down vote up
def CheckUrl(self, url, status_codes, max_retries=5):
    """Check a remote URL for availability.

    Args:
      url: A URL to access.
      status_codes: Acceptable status codes for the connection (list).
      max_retries: Number of retries before giving up.

    Returns:
      True if accessing the file produced one of status_codes.
    """
    try:
      self._OpenStream(url, max_retries=max_retries, status_codes=status_codes)
      return True
    except DownloadError as e:
      logging.error(e)
    return False 
Example 21
Project: glazier   Author: google   File: download.py    License: Apache License 2.0 6 votes vote down vote up
def _StoreDebugInfo(self, file_stream, socket_error=None):
    """Gathers debug information for use when file downloads fail.

    Args:
      file_stream:  The file stream object of the file being downloaded.
      socket_error: Store the error raised from the socket class with
        other debug info.

    Returns:
      debug_info:  A dictionary containing various pieces of debugging
          information.
    """
    if socket_error:
      self._debug_info['socket_error'] = socket_error
    if file_stream:
      for header in file_stream.info().header_items():
        self._debug_info[header[0]] = header[1]
    self._debug_info['current_time'] = time.strftime(
        '%A, %d %B %Y %H:%M:%S UTC') 
Example 22
Project: rtp_cluster   Author: sippy   File: DNRelay.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def deliver_dnotify(self, dnstring, _recurse = 0):
        if self.s == None:
            self.connect()
        if _recurse > _MAX_RECURSE:
            raise Exception('Cannot reconnect: %s', self.spath)
        if not dnstring.endswith('\n'):
            dnstring += '\n'
        while True:
            try:
                self.s.send(dnstring)
                break
            except socket.error as why:
                if why[0] == EINTR:
                    continue
                elif why[0] in (EPIPE, ENOTCONN, ECONNRESET):
                    self.s = None
                    return self.deliver_dnotify(dnstring, _recurse + 1)
                raise why
        # Clean any incoming data on the socket
        if len(self.poller.poll(0)) > 0:
            try:
                self.s.recv(1024)
            except:
                pass
        return 
Example 23
Project: rtp_cluster   Author: sippy   File: CLIManager.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def run(self):
        #print(self.run, 'enter')
        while True:
            #print(self.run, 'cycle')
            pollret = dict(self.pollobj.poll()).get(self.fileno, 0)
            if pollret & POLLNVAL != 0:
                break
            if pollret & POLLIN == 0:
                continue
            try:
                clientsock, addr = self.clicm.serversock.accept()
            except Exception as why:
                if isinstance(why, socket.error):
                    if why.errno == ECONNABORTED:
                        continue
                    elif why.errno == EBADF:
                        break
                    else:
                        raise
                dump_exception('CLIConnectionManager: unhandled exception when accepting incoming connection')
                break
            #print(self.run, 'handle_accept')
            ED2.callFromThread(self.clicm.handle_accept, clientsock, addr)
        self.clicm = None
        #print(self.run, 'exit') 
Example 24
Project: ffplayout-engine   Author: ffplayout   File: utils.py    License: GNU General Public License v3.0 6 votes vote down vote up
def validate_ffmpeg_libs():
    if 'libx264' not in FF_LIBS['libs']:
        playout_logger.error('ffmpeg contains no libx264!')
    if 'libfdk-aac' not in FF_LIBS['libs']:
        playout_logger.warning(
            'ffmpeg contains no libfdk-aac! No high quality aac...')
    if 'libtwolame' not in FF_LIBS['libs']:
        playout_logger.warning(
            'ffmpeg contains no libtwolame!'
            ' Loudness correction use mp2 audio codec...')
    if 'tpad' not in FF_LIBS['filters']:
        playout_logger.error('ffmpeg contains no tpad filter!')
    if 'zmq' not in FF_LIBS['filters']:
        playout_logger.error(
            'ffmpeg contains no zmq filter!  Text messages will not work...')


# ------------------------------------------------------------------------------
# probe media infos
# ------------------------------------------------------------------------------ 
Example 25
Project: ffplayout-engine   Author: ffplayout   File: utils.py    License: GNU General Public License v3.0 6 votes vote down vote up
def ffmpeg_stderr_reader(std_errors, decoder):
    if decoder:
        logger = decoder_logger
        prefix = DEC_PREFIX
    else:
        logger = encoder_logger
        prefix = ENC_PREFIX

    try:
        for line in std_errors:
            if _log.ff_level == 'INFO':
                logger.info('{}{}'.format(
                    prefix, line.decode("utf-8").rstrip()))
            elif _log.ff_level == 'WARNING':
                logger.warning('{}{}'.format(
                    prefix, line.decode("utf-8").rstrip()))
            else:
                logger.error('{}{}'.format(
                    prefix, line.decode("utf-8").rstrip()))
    except ValueError:
        pass 
Example 26
Project: oscrypto   Author: wbond   File: _socket_server.py    License: MIT License 6 votes vote down vote up
def listen(server, on_read):
    sock, addr = server.accept()

    timeout = 10
    try:
        read_ready, _, _ = select.select([sock], [], [], timeout)
        while len(read_ready):
            data = sock.recv(8192)
            if on_read(sock, data):
                read_ready, _, _ = select.select([sock], [], [], 0)
            else:
                read_ready = []
    except (socket.error, select.error, OSError, ValueError):
        pass
    try:
        sock.shutdown(socket.SHUT_RDWR)
    except (socket.error, OSError, ValueError):
        pass
    sock.close() 
Example 27
Project: oscrypto   Author: wbond   File: _socket_proxy.py    License: MIT License 6 votes vote down vote up
def proxy(src, dst, callback=None):
    timeout = 10
    try:
        read_ready, _, _ = select.select([src], [], [], timeout)
        while len(read_ready):
            if callback:
                callback(src, dst)
            else:
                dst.send(src.recv(8192))
            read_ready, _, _ = select.select([src], [], [], timeout)
    except (socket.error, select.error, OSError, ValueError):
        pass
    try:
        src.shutdown(socket.SHUT_RDWR)
    except (socket.error, OSError, ValueError):
        pass
    src.close()
    try:
        dst.shutdown(socket.SHUT_RDWR)
    except (socket.error, OSError, ValueError):
        pass
    dst.close() 
Example 28
Project: oscrypto   Author: wbond   File: tls.py    License: MIT License 6 votes vote down vote up
def _raw_read(self):
        """
        Reads data from the socket and writes it to the memory bio
        used by libssl to decrypt the data. Returns the unencrypted
        data for the purpose of debugging handshakes.

        :return:
            A byte string of ciphertext from the socket. Used for
            debugging the handshake only.
        """

        data = self._raw_bytes
        try:
            data += self._socket.recv(8192)
        except (socket_.error):
            pass
        output = data
        written = libssl.BIO_write(self._rbio, data, len(data))
        self._raw_bytes = data[written:]
        return output 
Example 29
Project: oscrypto   Author: wbond   File: tls.py    License: MIT License 6 votes vote down vote up
def _read_remaining(socket):
    """
    Reads everything available from the socket - used for debugging when there
    is a protocol error

    :param socket:
        The socket to read from

    :return:
        A byte string of the remaining data
    """

    output = b''
    old_timeout = socket.gettimeout()
    try:
        socket.settimeout(0.0)
        output += socket.recv(8192)
    except (socket_.error):
        pass
    finally:
        socket.settimeout(old_timeout)
    return output 
Example 30
Project: RF-Monitor   Author: EarToEarOak   File: server.py    License: GNU General Public License v2.0 5 votes vote down vote up
def send(self, data):
        if self._client is not None:
            try:
                self._client.sendall(data)
                self._client.sendall('\r\n')
            except socket.error:
                self._client.close()
                self._client = None