Python errno.EINPROGRESS Examples

The following are 30 code examples of errno.EINPROGRESS(). 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 errno , or try the search function .
Example #1
Source File: link.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def connect(self, address):
        """
        Try to make an actual connection.
        :return: True if connected
        """
        sock = self._connectors[address]
        err = sock.connect()

        self.poller.register(sock)
        self._sock_by_fd[sock.fileno()] = sock
        self._socks_waiting_to_connect.add(sock)

        if err in (0, errno.EISCONN):
            self.handle_connect(sock)
            return True
        elif err in (errno.ECONNREFUSED, errno.ENETUNREACH):
            self.handle_conn_refused(sock)
        elif err not in (errno.EINPROGRESS, errno.EWOULDBLOCK):
            raise socket.error(err, errno.errorcode[err])

        return False

    ########################################################## 
Example #2
Source File: stream.py    From ryu with Apache License 2.0 6 votes vote down vote up
def open_block((error, stream)):
        """Blocks until a Stream completes its connection attempt, either
        succeeding or failing.  (error, stream) should be the tuple returned by
        Stream.open().  Returns a tuple of the same form.

        Typical usage:
        error, stream = Stream.open_block(Stream.open("unix:/tmp/socket"))"""

        if not error:
            while True:
                error = stream.connect()
                if error != errno.EAGAIN:
                    break
                stream.run()
                poller = ovs.poller.Poller()
                stream.run_wait(poller)
                stream.connect_wait(poller)
                poller.block()
            assert error != errno.EINPROGRESS

        if error and stream:
            stream.close()
            stream = None
        return error, stream 
Example #3
Source File: stream.py    From ryu with Apache License 2.0 6 votes vote down vote up
def open(name, dscp=DSCP_DEFAULT):
        """Attempts to connect a stream to a remote peer.  'name' is a
        connection name in the form "TYPE:ARGS", where TYPE is an active stream
        class's name and ARGS are stream class-specific.  Currently the only
        supported TYPEs are "unix" and "tcp".

        Returns (error, stream): on success 'error' is 0 and 'stream' is the
        new Stream, on failure 'error' is a positive errno value and 'stream'
        is None.

        Never returns errno.EAGAIN or errno.EINPROGRESS.  Instead, returns 0
        and a new Stream.  The connect() method can be used to check for
        successful connection completion."""
        cls = Stream._find_method(name)
        if not cls:
            return errno.EAFNOSUPPORT, None

        suffix = name.split(":", 1)[1]
        error, sock = cls._open(suffix, dscp)
        if error:
            return error, None
        else:
            status = ovs.socket_util.check_connection_completion(sock)
            return 0, Stream(sock, name, status) 
Example #4
Source File: asyncadapter.py    From plex-for-kodi with GNU General Public License v2.0 6 votes vote down vote up
def _connect(self, sock, sa):
        while not self._canceled and not ABORT_FLAG_FUNCTION():
            time.sleep(0.01)
            self._check_timeout()  # this should be done at the beginning of each loop
            status = sock.connect_ex(sa)
            if not status or status in (errno.EISCONN, WIN_EISCONN):
                break
            elif status in (errno.EINPROGRESS, WIN_EWOULDBLOCK):
                self.deadline = time.time() + self._timeout.getConnectTimeout()
            # elif status in (errno.EWOULDBLOCK, errno.EALREADY) or (os.name == 'nt' and status == errno.WSAEINVAL):
            #     pass
            yield

        if self._canceled or ABORT_FLAG_FUNCTION():
            raise CanceledException('Request canceled')

        error = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
        if error:
            # TODO: determine when this case can actually happen
            raise socket.error((error,)) 
Example #5
Source File: client.py    From profiling with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def connect(self):
        while True:
            errno = self.sock.connect_ex(self.addr)
            if not errno:
                # connected immediately.
                break
            elif errno == EINPROGRESS:
                # will be connected.
                break
            elif errno == ENOENT:
                # no such socket file.
                self.create_connection(self.failover_interval)
                return
            else:
                raise ValueError('Unexpected socket errno: %d' % errno)
        self.event_loop.watch_file(self.sock.fileno(), self.handle) 
Example #6
Source File: client.py    From aws-iot-device-sdk-python with Apache License 2.0 6 votes vote down vote up
def _socketpair_compat():
    """TCP/IP socketpair including Windows support"""
    listensock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listensock.bind(("127.0.0.1", 0))
    listensock.listen(1)

    iface, port = listensock.getsockname()
    sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    sock1.setblocking(0)
    try:
        sock1.connect(("127.0.0.1", port))
    except socket.error as err:
        if err.errno != errno.EINPROGRESS and err.errno != errno.EWOULDBLOCK and err.errno != EAGAIN:
            raise
    sock2, address = listensock.accept()
    sock2.setblocking(0)
    listensock.close()
    return (sock1, sock2) 
Example #7
Source File: asyncredis.py    From collection with MIT License 6 votes vote down vote up
def __init__ (self):
		self.sock = None		# socket object
		self.send_buf = []		# send buffer
		self.recv_buf = []		# recv buffer
		self.pend_buf = ''		# send pending
		self.state = NET_STATE_CLOSED
		self.errd = [ errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK ]
		self.conn = ( errno.EISCONN, 10057, 10053 )
		self.errc = 0
		self.ipv6 = False
		self.eintr = ()
		if 'EINTR' in errno.__dict__:
			self.eintr = (errno.__dict__['EINTR'],)
		if 'WSAEWOULDBLOCK' in errno.__dict__:
			self.errd.append(errno.WSAEWOULDBLOCK)
		self.errd = tuple(self.errd)
		self.timeout = 0
		self.timecon = 0 
Example #8
Source File: recipe-577662.py    From code with MIT License 6 votes vote down vote up
def asyncConnect(self, address, callback):
    if (self.__acceptCallback):
      raise AsyncException('Accept already in progress')
    if (self.__connectCallback):
      raise AsyncException('Connect already in progress')
    if (self.__readCallback):
      raise AsyncException('Read already in progress')
    if (self.__writeAllCallback):
      raise AsyncException('Write all already in progress')
    if (self.__closed):
      raise AsyncException('AsyncSocket closed')

    err = self.__socket.connect_ex(address)
    if err in (errno.EINPROGRESS, errno.EWOULDBLOCK):
      self.__connectCallback = callback
      self.__asyncIOService.registerAsyncSocketForWrite(self)
    else:
      self.__asyncIOService.invokeLater(
        functools.partial(callback, err = err)) 
Example #9
Source File: client.py    From ParadoxIP150v2 with Eclipse Public License 1.0 6 votes vote down vote up
def _socketpair_compat():
    """TCP/IP socketpair including Windows support"""
    listensock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listensock.bind(("127.0.0.1", 0))
    listensock.listen(1)

    iface, port = listensock.getsockname()
    sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    sock1.setblocking(0)
    try:
        sock1.connect(("localhost", port))
    except socket.error as err:
        if err.errno != errno.EINPROGRESS and err.errno != errno.EWOULDBLOCK and err.errno != EAGAIN:
            raise
    sock2, address = listensock.accept()
    sock2.setblocking(0)
    listensock.close()
    return (sock1, sock2) 
Example #10
Source File: process.py    From pymesos with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, addr, callback):
        host, port = addr.split(':', 2)
        port = int(port)
        self._addr = (host, port)
        self._sock = socket.socket()
        self._sock.setblocking(0)
        self.connected = False
        try:
            self._sock.connect(self._addr)
        except socket.error as e:
            if e.errno != errno.EAGAIN and e.errno != errno.EINPROGRESS:
                raise
        self._parser = HttpParser()
        self._callback = callback
        self._stream_id = None
        self._request = callback.gen_request()
        self._response = b'' 
Example #11
Source File: multicast-relay.py    From multicast-relay with GNU General Public License v3.0 6 votes vote down vote up
def connectRemotes(self):
        for remote in self.remoteAddrs:
            if remote['socket']:
                continue

            # Attempt reconnection at most once every N seconds
            if remote['connectFailure'] and remote['connectFailure'] > time.time()-self.remoteRetry:
                return

            remoteConnection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            remoteConnection.setblocking(0)
            self.logger.info('REMOTE: Connecting to remote %s' % remote['addr'])
            remote['connecting'] = True
            try:
                remoteConnection.connect((remote['addr'], self.remotePort))
            except socket.error as e:
                if e.errno == errno.EINPROGRESS:
                    remote['socket'] = remoteConnection
                else:
                    remote['connecting'] = False
                    remote['connectFailure'] = time.time() 
Example #12
Source File: manager.py    From Dockerfiles with Apache License 2.0 5 votes vote down vote up
def _send_control_data(self, data):
        if self._control_client_addr:
            try:
                self._control_socket.sendto(data, self._control_client_addr)
            except (socket.error, OSError, IOError) as e:
                error_no = eventloop.errno_from_exception(e)
                if error_no in (errno.EAGAIN, errno.EINPROGRESS,
                                errno.EWOULDBLOCK):
                    return
                else:
                    shell.print_exception(e)
                    if self._config['verbose']:
                        traceback.print_exc() 
Example #13
Source File: tcprelay.py    From ssr-ml with Apache License 2.0 5 votes vote down vote up
def handle_event(self, sock, fd, event):
        # handle events and dispatch to handlers
        if sock:
            logging.log(shell.VERBOSE_LEVEL, 'fd %d %s', fd,
                        eventloop.EVENT_NAMES.get(event, event))
        if sock == self._server_socket:
            if event & eventloop.POLL_ERR:
                # TODO
                raise Exception('server_socket error')
            try:
                logging.debug('accept')
                conn = self._server_socket.accept()
                handler = TCPRelayHandler(self, self._fd_to_handlers,
                                self._eventloop, conn[0], self._config,
                                self._dns_resolver, self._is_local)
                if handler.stage() == STAGE_DESTROYED:
                    conn[0].close()
            except (OSError, IOError) as e:
                error_no = eventloop.errno_from_exception(e)
                if error_no in (errno.EAGAIN, errno.EINPROGRESS,
                                errno.EWOULDBLOCK):
                    return
                else:
                    shell.print_exception(e)
                    if self._config['verbose']:
                        traceback.print_exc()
        else:
            if sock:
                handler = self._fd_to_handlers.get(fd, None)
                if handler:
                    handler.handle_event(sock, event)
            else:
                logging.warn('poll removed fd') 
Example #14
Source File: manager.py    From SSRSpeed with GNU General Public License v3.0 5 votes vote down vote up
def _send_control_data(self, data):
        if self._control_client_addr:
            try:
                self._control_socket.sendto(data, self._control_client_addr)
            except (socket.error, OSError, IOError) as e:
                error_no = eventloop.errno_from_exception(e)
                if error_no in (errno.EAGAIN, errno.EINPROGRESS,
                                errno.EWOULDBLOCK):
                    return
                else:
                    shell.print_exception(e)
                    if self._config['verbose']:
                        traceback.print_exc() 
Example #15
Source File: tcprelay.py    From shadowsocks with Apache License 2.0 5 votes vote down vote up
def handle_event(self, sock, fd, event):
        # handle events and dispatch to handlers
        if sock:
            logging.log(shell.VERBOSE_LEVEL, 'fd %d %s', fd,
                        eventloop.EVENT_NAMES.get(event, event))
        if sock == self._server_socket:
            if event & eventloop.POLL_ERR:
                # TODO
                raise Exception('server_socket error')
            try:
                logging.debug('accept')
                conn = self._server_socket.accept()
                TCPRelayHandler(self, self._fd_to_handlers,
                                self._eventloop, conn[0], self._config,
                                self._dns_resolver, self._is_local)
            except (OSError, IOError) as e:
                error_no = eventloop.errno_from_exception(e)
                if error_no in (errno.EAGAIN, errno.EINPROGRESS,
                                errno.EWOULDBLOCK):
                    return
                else:
                    shell.print_exception(e)
                    if self._config['verbose']:
                        traceback.print_exc()
        else:
            if sock:
                handler = self._fd_to_handlers.get(fd, None)
                if handler:
                    handler.handle_event(sock, event)
            else:
                logging.warn('poll removed fd') 
Example #16
Source File: manager.py    From ssrr with Apache License 2.0 5 votes vote down vote up
def _send_control_data(self, data):
        if self._control_client_addr:
            try:
                self._control_socket.sendto(data, self._control_client_addr)
            except (socket.error, OSError, IOError) as e:
                error_no = eventloop.errno_from_exception(e)
                if error_no in (errno.EAGAIN, errno.EINPROGRESS,
                                errno.EWOULDBLOCK):
                    return
                else:
                    shell.print_exception(e)
                    if self._config['verbose']:
                        traceback.print_exc() 
Example #17
Source File: tcprelay.py    From shadowsocks with Apache License 2.0 5 votes vote down vote up
def _handle_stage_connecting(self, data):
        if self._is_local:
            data = self._encryptor.encrypt(data)
        self._data_to_write_to_remote.append(data)
        if self._is_local and not self._fastopen_connected and \
                self._config['fast_open']:
            # for sslocal and fastopen, we basically wait for data and use
            # sendto to connect
            try:
                # only connect once
                self._fastopen_connected = True
                remote_sock = \
                    self._create_remote_socket(self._chosen_server[0],
                                               self._chosen_server[1])
                self._loop.add(remote_sock, eventloop.POLL_ERR, self._server)
                data = b''.join(self._data_to_write_to_remote)
                l = len(data)
                s = remote_sock.sendto(data, MSG_FASTOPEN, self._chosen_server)
                if s < l:
                    data = data[s:]
                    self._data_to_write_to_remote = [data]
                else:
                    self._data_to_write_to_remote = []
                self._update_stream(STREAM_UP, WAIT_STATUS_READWRITING)
            except (OSError, IOError) as e:
                if eventloop.errno_from_exception(e) == errno.EINPROGRESS:
                    # in this case data is not sent at all
                    self._update_stream(STREAM_UP, WAIT_STATUS_READWRITING)
                elif eventloop.errno_from_exception(e) == errno.ENOTCONN:
                    logging.error('fast open not supported on this OS')
                    self._config['fast_open'] = False
                    self.destroy()
                else:
                    shell.print_exception(e)
                    if self._config['verbose']:
                        traceback.print_exc()
                    self.destroy() 
Example #18
Source File: tcprelay.py    From shadowsocks with Apache License 2.0 5 votes vote down vote up
def _write_to_sock(self, data, sock):
        # write data to sock
        # if only some of the data are written, put remaining in the buffer
        # and update the stream to wait for writing
        if not data or not sock:
            return False
        uncomplete = False
        try:
            l = len(data)
            s = sock.send(data)
            if s < l:
                data = data[s:]
                uncomplete = True
        except (OSError, IOError) as e:
            error_no = eventloop.errno_from_exception(e)
            if error_no in (errno.EAGAIN, errno.EINPROGRESS,
                            errno.EWOULDBLOCK):
                uncomplete = True
            else:
                shell.print_exception(e)
                self.destroy()
                return False
        if uncomplete:
            if sock == self._local_sock:
                self._data_to_write_to_local.append(data)
                self._update_stream(STREAM_DOWN, WAIT_STATUS_WRITING)
            elif sock == self._remote_sock:
                self._data_to_write_to_remote.append(data)
                self._update_stream(STREAM_UP, WAIT_STATUS_WRITING)
            else:
                logging.error('write_all_to_sock:unknown socket')
        else:
            if sock == self._local_sock:
                self._update_stream(STREAM_DOWN, WAIT_STATUS_READING)
            elif sock == self._remote_sock:
                self._update_stream(STREAM_UP, WAIT_STATUS_READING)
            else:
                logging.error('write_all_to_sock:unknown socket')
        return True 
Example #19
Source File: query.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def _connect(s, address):
    try:
        s.connect(address)
    except socket.error:
        (ty, v) = sys.exc_info()[:2]
        if v[0] != errno.EINPROGRESS and \
               v[0] != errno.EWOULDBLOCK and \
               v[0] != errno.EALREADY:
            raise v 
Example #20
Source File: manager.py    From shadowsocks with Apache License 2.0 5 votes vote down vote up
def _send_control_data(self, data):
        if self._control_client_addr:
            try:
                self._control_socket.sendto(data, self._control_client_addr)
            except (socket.error, OSError, IOError) as e:
                error_no = eventloop.errno_from_exception(e)
                if error_no in (errno.EAGAIN, errno.EINPROGRESS,
                                errno.EWOULDBLOCK):
                    return
                else:
                    shell.print_exception(e)
                    if self._config['verbose']:
                        traceback.print_exc() 
Example #21
Source File: manager.py    From ssr-ml with Apache License 2.0 5 votes vote down vote up
def _send_control_data(self, data):
        if self._control_client_addr:
            try:
                self._control_socket.sendto(data, self._control_client_addr)
            except (socket.error, OSError, IOError) as e:
                error_no = eventloop.errno_from_exception(e)
                if error_no in (errno.EAGAIN, errno.EINPROGRESS,
                                errno.EWOULDBLOCK):
                    return
                else:
                    shell.print_exception(e)
                    if self._config['verbose']:
                        traceback.print_exc() 
Example #22
Source File: manager.py    From shadowsocksR-b with Apache License 2.0 5 votes vote down vote up
def _send_control_data(self, data):
        if self._control_client_addr:
            try:
                self._control_socket.sendto(data, self._control_client_addr)
            except (socket.error, OSError, IOError) as e:
                error_no = eventloop.errno_from_exception(e)
                if error_no in (errno.EAGAIN, errno.EINPROGRESS,
                                errno.EWOULDBLOCK):
                    return
                else:
                    shell.print_exception(e)
                    if self._config['verbose']:
                        traceback.print_exc() 
Example #23
Source File: recipe-577662.py    From code with MIT License 5 votes vote down vote up
def handleWrite(self):
    if (self.__connectCallback):
      err = self.__socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
      if err not in (errno.EINPROGRESS, errno.EWOULDBLOCK):
        self.__asyncIOService.unregisterAsyncSocketForWrite(self)
        self.__asyncIOService.invokeLater(
          functools.partial(self.__connectCallback, err = err))
        self.__connectCallback = None

    if (self.__writeAllCallback):
      try:
        bytesSent = self.__socket.send(self.__writeBuffer)
        self.__writeBuffer = self.__writeBuffer[bytesSent:]
        if (len(self.__writeBuffer) == 0):
          self.__asyncIOService.unregisterAsyncSocketForWrite(self)
          self.__asyncIOService.invokeLater(
            functools.partial(self.__writeAllCallback, err = 0))
          self.__writeAllCallback = None
      except socket.error as e:
        if e.args[0] in (errno.EAGAIN, errno.EWOULDBLOCK):
          pass
        else:
          self.__asyncIOService.unregisterAsyncSocketForWrite(self)
          self.__asyncIOService.invokeLater(
            functools.partial(self.__writeAllCallback, err = e.args[0]))
          self.__writeAllCallback = None 
Example #24
Source File: test_epoll.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def _connected_pair(self):
        client = socket.socket()
        client.setblocking(False)
        try:
            client.connect(('127.0.0.1', self.serverSocket.getsockname()[1]))
        except OSError as e:
            self.assertEqual(e.args[0], errno.EINPROGRESS)
        else:
            raise AssertionError("Connect should have raised EINPROGRESS")
        server, addr = self.serverSocket.accept()

        self.connections.extend((client, server))
        return client, server 
Example #25
Source File: test_ssl.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_non_blocking_connect_ex(self):
        # Issue #11326: non-blocking connect_ex() should allow handshake
        # to proceed after the socket gets ready.
        with support.transient_internet(REMOTE_HOST):
            s = ssl.wrap_socket(socket.socket(socket.AF_INET),
                                cert_reqs=ssl.CERT_REQUIRED,
                                ca_certs=REMOTE_ROOT_CERT,
                                do_handshake_on_connect=False)
            try:
                s.setblocking(False)
                rc = s.connect_ex((REMOTE_HOST, 443))
                # EWOULDBLOCK under Windows, EINPROGRESS elsewhere
                self.assertIn(rc, (0, errno.EINPROGRESS, errno.EWOULDBLOCK))
                # Wait for connect to finish
                select.select([], [s], [], 5.0)
                # Non-blocking handshake
                while True:
                    try:
                        s.do_handshake()
                        break
                    except ssl.SSLWantReadError:
                        select.select([s], [], [], 5.0)
                    except ssl.SSLWantWriteError:
                        select.select([], [s], [], 5.0)
                # SSL established
                self.assertTrue(s.getpeercert())
            finally:
                s.close() 
Example #26
Source File: query.py    From script.elementum.burst with Do What The F*ck You Want To Public License 5 votes vote down vote up
def _connect(s, address):
    try:
        s.connect(address)
    except socket.error:
        (ty, v) = sys.exc_info()[:2]

        if hasattr(v, 'errno'):
            v_err = v.errno
        else:
            v_err = v[0]
        if v_err not in [errno.EINPROGRESS, errno.EWOULDBLOCK, errno.EALREADY]:
            raise v 
Example #27
Source File: iostream.py    From honeything with GNU General Public License v3.0 5 votes vote down vote up
def connect(self, address, callback=None):
        """Connects the socket to a remote address without blocking.

        May only be called if the socket passed to the constructor was
        not previously connected.  The address parameter is in the
        same format as for socket.connect, i.e. a (host, port) tuple.
        If callback is specified, it will be called when the
        connection is completed.

        Note that it is safe to call IOStream.write while the
        connection is pending, in which case the data will be written
        as soon as the connection is ready.  Calling IOStream read
        methods before the socket is connected works on some platforms
        but is non-portable.
        """
        self._connecting = True
        try:
            self.socket.connect(address)
        except socket.error, e:
            # In non-blocking mode we expect connect() to raise an
            # exception with EINPROGRESS or EWOULDBLOCK.
            #
            # On freebsd, other errors such as ECONNREFUSED may be
            # returned immediately when attempting to connect to
            # localhost, so handle them the same way as an error
            # reported later in _handle_connect.
            if e.args[0] not in (errno.EINPROGRESS, errno.EWOULDBLOCK):
                #logging.warning("Connect error on fd %d: %s",
                #                self.socket.fileno(), e)
                ht.logger.warning("Connect error on fd %d: %s",
                                self.socket.fileno(), e)
                self.close()
                return 
Example #28
Source File: test_iocp.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def _acceptAddressTest(self, family, localhost):
        """
        Create a C{SOCK_STREAM} connection to localhost using a socket with an
        address family of C{family} and assert that the result of
        L{iocpsupport.get_accept_addrs} is consistent with the result of
        C{socket.getsockname} and C{socket.getpeername}.
        """
        msg("family = %r" % (family,))
        port = socket(family, SOCK_STREAM)
        self.addCleanup(port.close)
        port.bind(('', 0))
        port.listen(1)
        client = socket(family, SOCK_STREAM)
        self.addCleanup(client.close)
        client.setblocking(False)
        try:
            client.connect((localhost, port.getsockname()[1]))
        except error as e:
            self.assertIn(e.errno, (errno.EINPROGRESS, errno.EWOULDBLOCK))

        server = socket(family, SOCK_STREAM)
        self.addCleanup(server.close)
        buff = array('B', b'\0' * 256)
        self.assertEqual(
            0, _iocp.accept(port.fileno(), server.fileno(), buff, None))
        server.setsockopt(
            SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT, pack('P', port.fileno()))
        self.assertEqual(
            (family, client.getpeername()[:2], client.getsockname()[:2]),
            _iocp.get_accept_addrs(server.fileno(), buff)) 
Example #29
Source File: test_tcp.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def _buildProtocolAddressTest(self, client, interface):
        """
        Connect C{client} to a server listening on C{interface} started with
        L{IReactorTCP.listenTCP} and return the address passed to the factory's
        C{buildProtocol} method.

        @param client: A C{SOCK_STREAM} L{socket.socket} created with an address
            family such that it will be able to connect to a server listening on
            C{interface}.

        @param interface: A C{str} giving an address for a server to listen on.
            This should almost certainly be the loopback address for some
            address family supported by L{IReactorTCP.listenTCP}.

        @return: Whatever object, probably an L{IAddress} provider, is passed to
            a server factory's C{buildProtocol} method when C{client}
            establishes a connection.
        """
        class ObserveAddress(ServerFactory):
            def buildProtocol(self, address):
                reactor.stop()
                self.observedAddress = address
                return Protocol()

        factory = ObserveAddress()
        reactor = self.buildReactor()
        port = self.getListeningPort(reactor, factory, 0, interface)
        client.setblocking(False)
        try:
            connect(client, (port.getHost().host, port.getHost().port))
        except socket.error as e:
            self.assertIn(e.errno, (errno.EINPROGRESS, errno.EWOULDBLOCK))

        self.runReactor(reactor)

        return factory.observedAddress 
Example #30
Source File: tcprelay.py    From ShadowsocksFork with Apache License 2.0 5 votes vote down vote up
def handle_event(self, sock, fd, event):
        # handle events and dispatch to handlers
        if sock:
            logging.log(shell.VERBOSE_LEVEL, 'fd %d %s', fd,
                        eventloop.EVENT_NAMES.get(event, event))
        if sock == self._server_socket:
            if event & eventloop.POLL_ERR:
                # TODO
                raise Exception('server_socket error')
            try:
                logging.debug('accept')
                conn = self._server_socket.accept()
                TCPRelayHandler(self, self._fd_to_handlers,
                                self._eventloop, conn[0], self._config,
                                self._dns_resolver, self._is_local)
            except (OSError, IOError) as e:
                error_no = eventloop.errno_from_exception(e)
                if error_no in (errno.EAGAIN, errno.EINPROGRESS,
                                errno.EWOULDBLOCK):
                    return
                else:
                    shell.print_exception(e)
                    if self._config['verbose']:
                        traceback.print_exc()
        else:
            if sock:
                handler = self._fd_to_handlers.get(fd, None)
                if handler:
                    handler.handle_event(sock, event)
            else:
                logging.warn('poll removed fd')