我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用errno.EINPROGRESS。
def _socketpair(): if hasattr(socket, 'socketpair'): return socket.socketpair() srv_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) srv_sock.bind(('127.0.0.1', 0)) srv_sock.listen(1) write_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: write_sock.setblocking(False) try: write_sock.connect(srv_sock.getsockname()[:2]) except socket.error as e: if e.args[0] in (EINPROGRESS, EWOULDBLOCK): pass else: raise write_sock.setblocking(True) read_sock = srv_sock.accept()[0] except: write_sock.close() raise finally: srv_sock.close() return (read_sock, write_sock)
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)
def _connectedPair(self): """ Return the two sockets which make up a new TCP connection. """ client = socket.socket() client.setblocking(False) try: client.connect(('127.0.0.1', self.serverSocket.getsockname()[1])) except socket.error, e: self.assertEquals(e.args[0], errno.EINPROGRESS) else: raise unittest.FailTest("Connect should have raised EINPROGRESS") server, addr = self.serverSocket.accept() self.connections.extend((client, server)) return client, server
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)
def reset_input_buffer(self): """Clear input buffer, discarding all that is in the buffer.""" if not self.is_open: raise portNotOpenError # just use recv to remove input, while there is some ready = True while ready: ready, _, _ = select.select([self._socket], [], [], 0) try: self._socket.recv(4096) except OSError as e: # this is for Python 3.x where select.error is a subclass of # OSError ignore BlockingIOErrors and EINTR. other errors are shown # https://www.python.org/dev/peps/pep-0475. if e.errno not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR): raise SerialException('read failed: {}'.format(e)) except (select.error, socket.error) as e: # this is for Python 2.x # ignore BlockingIOErrors and EINTR. all errors are shown # see also http://www.python.org/dev/peps/pep-3151/#select if e[0] not in (errno.EAGAIN, errno.EALREADY, errno.EWOULDBLOCK, errno.EINPROGRESS, errno.EINTR): raise SerialException('read failed: {}'.format(e))
def __init__(self, head = HEAD_WORD_LSB): self.sock = None # socket object self.send_buf = '' # send buffer self.recv_buf = '' # recv buffer self.state = NET_STATE_STOP self.errd = [ errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK ] self.conn = ( errno.EISCONN, 10057, 10053 ) self.errc = 0 self.headmsk = False self.headraw = False self.__head_init(head) self.crypts = None self.cryptr = None 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.block = False
def make_socket(proto, addr, source=None, source_port=0): af = ip_family(addr[0]) if pysocks: sock = pysocks.socksocket(af, proto, 0) else: sock = socket.socket(af, proto, 0) sock.setblocking(0) if source is None: source = {socket.AF_INET: '0.0.0.0', socket.AF_INET6: '::'}[af] try: sock.bind((source, source_port,)) sock.connect(addr) except socket.error as e: if e.args == errno.EINPROGRESS: pass return sock
def connectThread(self): while not self.connected: try: self.client.connect((HOST, PORT)) except socket.error as e: pass finally: if e.errno == errno.EINPROGRESS: time.sleep(1.0) elif e.errno == errno.ECONNREFUSED: time.sleep(1.0) elif e.errno == errno.EALREADY: time.sleep(1.0) elif e.errno == errno.EINVAL: break elif e.errno == errno.EISCONN: logger.log("[button]: Connected to Artoo.") self.connected = True self.buttonsInitialized = False else: logger.log("[button]: Unexpected socket exception: %s" % e) time.sleep(1.0)
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 sys.platform == "win32": if error_no in (errno.EAGAIN, errno.EINPROGRESS, errno.EWOULDBLOCK, errno.WSAEWOULDBLOCK): return elif error_no in (errno.EAGAIN, errno.EINPROGRESS, errno.EWOULDBLOCK): return else: shell.print_exception(e) if self._config['verbose']: traceback.print_exc()
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 connect() always raises an exception if e.args[0] not in (errno.EINPROGRESS, errno.EWOULDBLOCK): raise self._connect_callback = stack_context.wrap(callback) self._add_io_state(self.io_loop.WRITE)
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,))
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
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(("localhost", 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)
def connect_socket(host, port, blocking=True): """Create a TCP connection to the server.""" addr = socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM) if not addr: raise Exception("Could not translate address '%s:%s'" % (host, str(port))) my_socket = socket.socket(addr[0][0], addr[0][1], addr[0][2]) if not blocking: my_socket.setblocking(0) try: my_socket.connect(addr[0][4]) except socket.error as e: if e.errno != errno.EINPROGRESS: raise return my_socket
def server_socket(host, port, backlog=10): """Create a TCP listening socket for a server.""" addr = socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM) if not addr: raise Exception("Could not translate address '%s:%s'" % (host, str(port))) my_socket = socket.socket(addr[0][0], addr[0][1], addr[0][2]) my_socket.setblocking(0) # 0=non-blocking try: my_socket.bind(addr[0][4]) my_socket.listen(backlog) except socket.error as e: if e.errno != errno.EINPROGRESS: raise return my_socket
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()
def handle_urllib2_error(url, e): if e.errno == errno.EINPROGRESS or '[Errno 115]' in str(e): raise Exception( 'could not access: %s: operation timed out before completion ' '(raise the timeout value?)' % url ) elif isinstance(e, HTTPError): if e.getcode() == 403: raise Exception( "Host '%s' \n" "requires authentication, please add to jenkins.json\n" "format example:\n" "'auth' : {\n" "\t 'http://hostname' : {\n" "\t\t'method' : 'basic',\n" "\t\t'user' : 'username',\n" "\t\t'password' : 'pass'},\n" "\t 'http://hostname2...' : {'method' : None}\n" "}" % e.geturl() ) elif e.getcode() == 401: raise Exception( "Invalid authentication to '%s', please update jenkins.json.\n" "Note that this will happen with invalid credentials " "even if the host doesn't require authentication for access." % e.geturl() ) raise Exception('could not access %s: %s' % (url, e))
def connect(self): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setblocking(0) self.set_keepalive() try: self.socket.connect(self.address) except socket.error, e: if e.errno == errno.EINPROGRESS: raise ConnectionInProgress() raise
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
def connect(self, *addr): timeout = self.timeout sock = self.sock try: # Non-blocking mode sock.setblocking(0) sock.connect(*addr) sock.setblocking(timeout != 0) return 1 except socket.error,why: if not timeout: raise sock.setblocking(1) if len(why.args) == 1: code = 0 else: code, why = why if code not in ( errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK ): raise _,w,_ = select.select([],[sock],[],timeout) if w: try: sock.connect(*addr) return 1 except socket.error,why: if len(why.args) == 1: code = 0 else: code, why = why if code in (errno.EISCONN, WSAEINVAL): return 1 raise raise TimeoutError('socket connect() timeout.')
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
def _handle_stage_connecting(self, data): if self._is_local: data = self._protocol.client_pre_encrypt(data) data = self._encryptor.encrypt(data) data = self._obfs.client_encode(data) if 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()
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')
def connect(self, *addr): timeout = self.timeout sock = self.sock try: # Non-blocking mode sock.setblocking(0) apply(sock.connect, addr) sock.setblocking(timeout != 0) return 1 except socket.error,why: if not timeout: raise sock.setblocking(1) if len(why.args) == 1: code = 0 else: code, why = why if code not in ( errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK ): raise r,w,e = select.select([],[sock],[],timeout) if w: try: apply(sock.connect, addr) return 1 except socket.error,why: if len(why.args) == 1: code = 0 else: code, why = why if code in (errno.EISCONN, WSAEINVAL): return 1 raise raise TimeoutError('socket connect() timeout.')
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
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()
def connect(self, address): if self.timeout == 0.0: return self._sock.connect(address) sock = self._sock if isinstance(address, tuple): r = getaddrinfo(address[0], address[1], sock.family, sock.type, sock.proto) address = r[0][-1] if self.timeout is not None: timer = Timeout.start_new(self.timeout, timeout('timed out')) else: timer = None try: while True: err = sock.getsockopt(SOL_SOCKET, SO_ERROR) if err: raise error(err, strerror(err)) result = sock.connect_ex(address) if not result or result == EISCONN: break elif (result in (EWOULDBLOCK, EINPROGRESS, EALREADY)) or (result == EINVAL and is_windows): self._wait(self._write_event) else: raise error(result, strerror(result)) finally: if timer is not None: timer.cancel()
def connect(self, address): if isinstance(address, tuple) and len(address) == 2: address = gethostbyname(address[0]), address[1] if self.timeout == 0.0: return self._sock.connect(address) sock = self._sock if self.timeout is None: while True: err = sock.getsockopt(SOL_SOCKET, SO_ERROR) if err: raise error(err, strerror(err)) result = sock.connect_ex(address) if not result or result == EISCONN: break elif (result in (EWOULDBLOCK, EINPROGRESS, EALREADY)) or (result == EINVAL and is_windows): wait_readwrite(sock.fileno(), event=self._rw_event) else: raise error(result, strerror(result)) else: end = time.time() + self.timeout while True: err = sock.getsockopt(SOL_SOCKET, SO_ERROR) if err: raise error(err, strerror(err)) result = sock.connect_ex(address) if not result or result == EISCONN: break elif (result in (EWOULDBLOCK, EINPROGRESS, EALREADY)) or (result == EINVAL and is_windows): timeleft = end - time.time() if timeleft <= 0: raise timeout('timed out') wait_readwrite(sock.fileno(), timeout=timeleft, event=self._rw_event) else: raise error(result, strerror(result))