Python socket.error() Examples

The following are 30 code examples of socket.error(). 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 also want to check out all available functions/classes of the module socket , or try the search function .
Example #1
Source File: server.py    From RF-Monitor with GNU General Public License v2.0 10 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
Source File: utils.py    From ffplayout-engine with GNU General Public License v3.0 8 votes vote down vote up
def send_mail(self, msg):
        if _mail.recip:
            # write message to temp file for rate limit
            with open(self.temp_msg, 'w+') as f:
                f.write(msg)

            self.current_time()

            message = MIMEMultipart()
            message['From'] = _mail.s_addr
            message['To'] = _mail.recip
            message['Subject'] = _mail.subject
            message['Date'] = formatdate(localtime=True)
            message.attach(MIMEText('{} {}'.format(self.time, msg), 'plain'))
            text = message.as_string()

            try:
                server = smtplib.SMTP(_mail.server, _mail.port)
            except socket.error as err:
                playout_logger.error(err)
                server = None

            if server is not None:
                server.starttls()
                try:
                    login = server.login(_mail.s_addr, _mail.s_pass)
                except smtplib.SMTPAuthenticationError as serr:
                    playout_logger.error(serr)
                    login = None

                if login is not None:
                    server.sendmail(_mail.s_addr, _mail.recip, text)
                    server.quit() 
Example #3
Source File: tls.py    From oscrypto with 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 #4
Source File: lib.py    From iSDX with 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 #5
Source File: test_conn.py    From cherrypy with 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 #6
Source File: policy_loader.py    From iSDX with 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
Source File: lib.py    From iSDX with 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 #8
Source File: test_http.py    From cherrypy with 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 #9
Source File: L.E.S.M.A. - Fabrica de Noobs Speedtest.py    From L.E.S.M.A with 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 #10
Source File: tnode.py    From iSDX with 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 #11
Source File: TCP_generic.py    From XFLTReaT with 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
Source File: TCP_generic.py    From XFLTReaT with 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
Source File: SCTP_generic.py    From XFLTReaT with 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
Source File: WebSocket.py    From XFLTReaT with 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
Source File: UDP_generic.py    From XFLTReaT with 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 #16
Source File: gmacpyutil.py    From macops with 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 #17
Source File: firebase.py    From pyfirebase with 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 #18
Source File: Server.py    From EvilOSX with 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 #19
Source File: download.py    From glazier with 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 #20
Source File: download.py    From glazier with 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 #21
Source File: DNRelay.py    From rtp_cluster with 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 #22
Source File: CLIManager.py    From rtp_cluster with 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 #23
Source File: utils.py    From ffplayout-engine with 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 #24
Source File: utils.py    From ffplayout-engine with 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 #25
Source File: _socket_proxy.py    From oscrypto with 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 #26
Source File: tls.py    From oscrypto with 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 #27
Source File: UDP_generic.py    From XFLTReaT with 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 #28
Source File: Udp_server.py    From rtp_cluster with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run(self):
        maxemptydata = 100
        while True:
            try:
                data, address = self.userv.skt.recvfrom(8192)
                if not data and address == None:
                    # Ugly hack to detect socket being closed under us on Linux.
                    # The problem is that even call on non-closed socket can
                    # sometimes return empty data buffer, making AsyncReceiver
                    # to exit prematurely.
                    maxemptydata -= 1
                    if maxemptydata == 0:
                        break
                    continue
                else:
                    maxemptydata = 100
                rtime = MonoTime()
            except Exception as why:
                if isinstance(why, socket.error) and why.errno in (ECONNRESET, ENOTCONN, ESHUTDOWN):
                    break
                if isinstance(why, socket.error) and why.errno in (EINTR,):
                    continue
                else:
                    print(datetime.now(), 'Udp_server: unhandled exception when receiving incoming data')
                    print('-' * 70)
                    traceback.print_exc(file = sys.stdout)
                    print('-' * 70)
                    sys.stdout.flush()
                    sleep(1)
                    continue
            if self.userv.uopts.family == socket.AF_INET6:
                address = ('[%s]' % address[0], address[1])
            ED2.callFromThread(self.userv.handle_read, data, address, rtime)
        self.userv = None 
Example #29
Source File: Udp_server.py    From rtp_cluster with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run(self):
        while True:
            self.userv.wi_available.acquire()
            while len(self.userv.wi) == 0:
                self.userv.wi_available.wait()
            wi = self.userv.wi.pop(0)
            if wi == None:
                # Shutdown request, relay it further
                self.userv.wi.append(None)
                self.userv.wi_available.notify()
            self.userv.wi_available.release()
            if wi == None:
                break
            data, address = wi
            try:
                ai = socket.getaddrinfo(address[0], None, self.userv.uopts.family)
            except:
                continue
            if self.userv.uopts.family == socket.AF_INET:
                address = (ai[0][4][0], address[1])
            else:
                address = (ai[0][4][0], address[1], ai[0][4][2], ai[0][4][3])
            for i in range(0, 20):
                try:
                    if self.userv.skt.sendto(data, address) == len(data):
                        break
                except socket.error as why:
                    if isinstance(why, BrokenPipeError):
                        self.userv = None
                        return
                    if why.errno not in (EWOULDBLOCK, ENOBUFS, EAGAIN):
                        break
                sleep(0.01)
        self.userv = None 
Example #30
Source File: CLIManager.py    From rtp_cluster with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def shutdown(self):
        if self.wthr == None:
            return
        self.wthr.shutdown()
        try:
            self.clientsock.shutdown(socket.SHUT_RDWR)
        except Exception as e:
            if not isinstance(e, socket.error) or e.errno != ENOTCONN:
                dump_exception('self.clientsock.shutdown(socket.SHUT_RDWR)')
        self.clientsock.close()
        self.wthr = None
        self.rthr = None