我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用errno.ENOTCONN。
def send (self, data): try: numsent = self.socket.send (data) if numsent: self.set_event_time () return numsent except socket.error as why: if why.errno == EWOULDBLOCK: return 0 elif why.errno in asyncore._DISCONNECTED: #print (">>>>>>>>>> why.errno == asyncore.ENOTCONN", why.errno == asyncore.ENOTCONN) if os.name == "nt" and why.errno == asyncore.ENOTCONN: # winsock sometimes raise ENOTCONN and sometimes recovered. # Found this error at http://file.hungryboarder.com:8080/HBAdManager/pa.html?siteId=hboarder&zoneId=S-2 if self._raised_ENOTCONN <= 3: self._raised_ENOTCONN += 1 return 0 else: self._raised_ENOTCONN = 0 self.handle_close (700, "Connection closed unexpectedly in send") return 0 else: raise
def send(self, message, flags): with self.send_token: if not self.state.ESTABLISHED: self.err("send() in socket state {0}".format(self.state)) if self.state.CLOSE_WAIT: raise err.Error(errno.EPIPE) raise err.Error(errno.ENOTCONN) if len(message) > self.send_miu: raise err.Error(errno.EMSGSIZE) while self.send_window_slots == 0 and self.state.ESTABLISHED: if flags & nfc.llcp.MSG_DONTWAIT: raise err.Error(errno.EWOULDBLOCK) self.log("waiting on busy send window") self.send_token.wait() self.log("send {0} byte on {1}".format(len(message), str(self))) if self.state.ESTABLISHED: send_pdu = pdu.Information(self.peer, self.addr, data=message) send_pdu.ns = self.send_cnt self.send_cnt = (self.send_cnt + 1) % 16 super(DataLinkConnection, self).send(send_pdu, flags) return self.state.ESTABLISHED is True
def recv(self): with self.lock: if not (self.state.ESTABLISHED or self.state.CLOSE_WAIT): self.err("recv() in socket state {0}".format(self.state)) raise err.Error(errno.ENOTCONN) try: rcvd_pdu = super(DataLinkConnection, self).recv() except IndexError: return None if rcvd_pdu.name == "I": self.recv_confs += 1 if self.recv_confs > self.recv_win: self.err("recv_confs({0}) > recv_win({1})" .format(self.recv_confs, self.recv_win)) raise RuntimeError("recv_confs > recv_win") return rcvd_pdu.data if rcvd_pdu.name == "DISC": self.close() return None raise RuntimeError("only I or DISC expected, not " + rcvd_pdu.name)
def start_worker(cls, connection, address): try: RLXWorker.run(connection, address) except KeyboardInterrupt: pass finally: log.debug('Closing connection %s:%d' % address) if sys.platform == 'win32': os._exit(-1) else: try: connection.shutdown(socket.SHUT_RDWR) except socket.error as e: # we don't care if the socket is already closed; # this will often be the case if client closed connection first if e.errno != errno.ENOTCONN: raise finally: connection.close()
def send(self, message): with self.send_token: if not self.state.ESTABLISHED: self.err("send() in socket state {0}".format(self.state)) if self.state.CLOSE_WAIT: raise Error(errno.EPIPE) raise Error(errno.ENOTCONN) if len(message) > self.send_miu: raise Error(errno.EMSGSIZE) while self.send_window_slots == 0 and self.state.ESTABLISHED: self.log("waiting on busy send window") self.send_token.wait() self.log("send() {0}".format(str(self))) if self.state.ESTABLISHED: pdu = Information(self.peer, self.addr, sdu=message) pdu.ns = self.send_cnt self.send_cnt = (self.send_cnt + 1) % 16 super(DataLinkConnection, self).send(pdu) return self.state.ESTABLISHED == True
def recv(self): with self.lock: if not (self.state.ESTABLISHED or self.state.CLOSE_WAIT): self.err("recv() in socket state {0}".format(self.state)) raise Error(errno.ENOTCONN) try: pdu = super(DataLinkConnection, self).recv() except IndexError: return None if isinstance(pdu, Information): self.recv_confs += 1 if self.recv_confs > self.recv_win: self.err("recv_confs({0}) > recv_win({1})" .format(self.recv_confs, self.recv_win)) raise RuntimeError("recv_confs > recv_win") return pdu.sdu if isinstance(pdu, Disconnect): self.close() return None raise RuntimeError("only I or DISC expected, not "+ pdu.name)
def _send_loop(self, send_method, data, *args): if self.act_non_blocking: return send_method(data, *args) while 1: try: return send_method(data, *args) except socket.error as e: eno = get_errno(e) if eno == errno.ENOTCONN or eno not in SOCKET_BLOCKING: raise try: self._trampoline(self.fd, write=True, timeout=self.gettimeout(), timeout_exc=socket.timeout("timed out")) except IOClosed: raise socket.error(errno.ECONNRESET, 'Connection closed by another thread')
def shutdown_safe(sock): """ Shuts down the socket. This is a convenience method for code that wants to gracefully handle regular sockets, SSL.Connection sockets from PyOpenSSL and ssl.SSLSocket objects from Python 2.6 interchangeably. Both types of ssl socket require a shutdown() before close, but they have different arity on their shutdown method. Regular sockets don't need a shutdown before close, but it doesn't hurt. """ try: try: # socket, ssl.SSLSocket return sock.shutdown(socket.SHUT_RDWR) except TypeError: # SSL.Connection return sock.shutdown() except socket.error as e: # we don't care if the socket is already closed; # this will often be the case in an http server context if get_errno(e) not in (errno.ENOTCONN, errno.EBADF): raise
def close(self): """Close the connection without assuming anything about it.""" try: file = self.file self.file = None if file is not None: file.close() finally: sock = self.sock self.sock = None if sock is not None: try: sock.shutdown(socket.SHUT_RDWR) except OSError as e: # The server might already have closed the connection if e.errno != errno.ENOTCONN: raise finally: sock.close() #__del__ = quit # optional commands:
def is_routine_fatal(exc): """Return string if exception is non-error unrecoverable, None otherwise Used to suppress a stack trace for exceptions like keyboard interrupts or connection drops. Return value is string to use as an exit message. """ if isinstance(exc, exceptions.KeyboardInterrupt): return "User abort" elif isinstance(exc, connection.ConnectionError): return "Lost connection to the remote system" elif isinstance(exc, SignalException): return "Killed with signal %s" % (exc,) elif isinstance(exc, EnvironmentError) and exc.errno == errno.ENOTCONN: return ("Filesystem reports connection failure:\n%s" % exc) return None
def close(self): """Close the socket from connection instance.""" self.state = ConnectionState.FINISHED if self.switch and self.switch.connection is self: self.switch.connection = None LOG.debug('Shutting down Connection %s', self.id) try: self.socket.shutdown(SHUT_RDWR) self.socket.close() self.socket = None LOG.debug('Connection Closed: %s', self.id) except OSError as exception: if exception.errno not in (ENOTCONN, EBADF): raise exception except AttributeError as exception: LOG.debug('Socket Already Closed: %s', self.id)
def close(self): """Close the connection without assuming anything about it.""" if self.file is not None: self.file.close() if self.sock is not None: try: self.sock.shutdown(socket.SHUT_RDWR) except OSError as e: # The server might already have closed the connection if e.errno != errno.ENOTCONN: raise finally: self.sock.close() self.file = self.sock = None #__del__ = quit # optional commands:
def _send_loop(self, send_method, data, *args): if self.act_non_blocking: return send_method(data, *args) _timeout_exc = socket_timeout('timed out') while True: try: return send_method(data, *args) except socket.error as e: eno = get_errno(e) if eno == errno.ENOTCONN or eno not in SOCKET_BLOCKING: raise try: self._trampoline(self.fd, write=True, timeout=self.gettimeout(), timeout_exc=_timeout_exc) except IOClosed: raise socket.error(errno.ECONNRESET, 'Connection closed by another thread')
def shutdown_safe(sock): """ Shuts down the socket. This is a convenience method for code that wants to gracefully handle regular sockets, SSL.Connection sockets from PyOpenSSL and ssl.SSLSocket objects from Python 2.6 interchangeably. Both types of ssl socket require a shutdown() before close, but they have different arity on their shutdown method. Regular sockets don't need a shutdown before close, but it doesn't hurt. """ try: try: # socket, ssl.SSLSocket return sock.shutdown(socket.SHUT_RDWR) except TypeError: # SSL.Connection return sock.shutdown() except socket.error as e: # we don't care if the socket is already closed; # this will often be the case in an http server context if get_errno(e) not in (errno.ENOTCONN, errno.EBADF, errno.ENOTSOCK): raise
def connect_volume(self, connection_info, disk_info): """Connect the volume.""" data = connection_info['data'] quobyte_volume = self._normalize_export(data['export']) mount_path = self._get_mount_path(connection_info) mounted = libvirt_utils.is_mounted(mount_path, SOURCE_PROTOCOL + '@' + quobyte_volume) if mounted: try: os.stat(mount_path) except OSError as exc: if exc.errno == errno.ENOTCONN: mounted = False LOG.info(_LI('Fixing previous mount %s which was not' ' unmounted correctly.'), mount_path) umount_volume(mount_path) if not mounted: mount_volume(quobyte_volume, mount_path, CONF.libvirt.quobyte_client_cfg) validate_volume(mount_path)
def __init__(self, server, conn, addr): asynchat.async_chat.__init__(self, conn) self.__server = server self.__conn = conn self.__addr = addr self.__line = [] self.__state = self.COMMAND self.__greeting = 0 self.__mailfrom = None self.__rcpttos = [] self.__data = '' self.__fqdn = socket.getfqdn() try: self.__peer = conn.getpeername() except socket.error, err: # a race condition may occur if the other end is closing # before we can get the peername self.close() if err[0] != errno.ENOTCONN: raise return print >> DEBUGSTREAM, 'Peer:', repr(self.__peer) self.push('220 %s %s' % (self.__fqdn, __version__)) self.set_terminator('\r\n') # Overrides base class for convenience
def shutdown(self): """Close I/O established in "open".""" self.file.close() try: self.sock.shutdown(socket.SHUT_RDWR) except socket.error as e: # The server might already have closed the connection if e.errno != errno.ENOTCONN: raise finally: self.sock.close()
def endsocket(sock): if os.name != 'nt': try: sock.shutdown(getattr(socket, 'SHUT_RDWR', 2)) except socket.error, e: if e.errno != errno.ENOTCONN: raise sock.close()
def _check_connected(self): if not self._connected: # getpeername() will raise ENOTCONN if the socket is really # not connected; note that we can be connected even without # _connected being set, e.g. if connect() first returned # EAGAIN. self.getpeername()
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 test__sock_connect_cb_exception(self): f = asyncio.Future(loop=self.loop) sock = mock.Mock() sock.fileno.return_value = 10 sock.getsockopt.return_value = errno.ENOTCONN self.loop.remove_writer = mock.Mock() self.loop._sock_connect_cb(f, sock, ('127.0.0.1', 8080)) self.assertIsInstance(f.exception(), OSError)
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 forward_socket(local, remote, timeout, bufsize): """forward socket""" def __io_copy(dest, source, timeout): try: dest.settimeout(timeout) source.settimeout(timeout) while 1: data = source.recv(bufsize) if not data: break dest.sendall(data) except socket.timeout: pass except (socket.error, ssl.SSLError, OpenSSL.SSL.Error) as e: if e.args[0] not in (errno.ECONNABORTED, errno.ECONNRESET, errno.ENOTCONN, errno.EPIPE): raise if e.args[0] in (errno.EBADF,): return finally: for sock in (dest, source): try: sock.close() except StandardError: pass thread.start_new_thread(__io_copy, (remote.dup(), local.dup(), timeout)) __io_copy(local, remote, timeout)
def connected(self): try: self._conn.getpeername() except socket.error as e: if e.errno != errno.ENOTCONN: # It's an exception other than the one we expected if we're not # connected. raise return False return True # Lovingly stolen from CherryPy (http://svn.cherrypy.org/tags/cherrypy-3.2.1/cherrypy/wsgiserver/ssl_pyopenssl.py).
def __init__(self, sock, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version=PROTOCOL_SSLv23, ca_certs=None, do_handshake_on_connect=True, suppress_ragged_eofs=True, ciphers=None): socket.__init__(self, _sock=sock) if certfile and not keyfile: keyfile = certfile # see if it's connected try: socket.getpeername(self) except socket_error, e: if e[0] != errno.ENOTCONN: raise # no, no connection yet self._sslobj = None else: # yes, create the SSL object if ciphers is None: self._sslobj = _ssl.sslwrap(self._sock, server_side, keyfile, certfile, cert_reqs, ssl_version, ca_certs) else: self._sslobj = _ssl.sslwrap(self._sock, server_side, keyfile, certfile, cert_reqs, ssl_version, ca_certs, ciphers) if do_handshake_on_connect: self.do_handshake() self.keyfile = keyfile self.certfile = certfile self.cert_reqs = cert_reqs self.ssl_version = ssl_version self.ca_certs = ca_certs self.ciphers = ciphers self.do_handshake_on_connect = do_handshake_on_connect self.suppress_ragged_eofs = suppress_ragged_eofs self._makefile_refs = 0
def proxy_protocol_access_check(self): # check in allow list if isinstance(self.unreader, SocketUnreader): try: remote_host = self.unreader.sock.getpeername()[0] except socket.error as e: if e.args[0] == ENOTCONN: raise ForbiddenProxyRequest("UNKNOW") raise if ("*" not in self.cfg.proxy_allow_ips and remote_host not in self.cfg.proxy_allow_ips): raise ForbiddenProxyRequest(remote_host)
def __init__(self, server, conn, addr): asynchat.async_chat.__init__(self, conn) self.smtp_server = server self.conn = conn self.addr = addr self.received_lines = [] self.smtp_state = self.COMMAND self.seen_greeting = '' self.mailfrom = None self.rcpttos = [] self.received_data = '' self.fqdn = socket.getfqdn() self.num_bytes = 0 try: self.peer = conn.getpeername() except socket.error as err: # a race condition may occur if the other end is closing # before we can get the peername self.close() if err.args[0] != errno.ENOTCONN: raise return print('Peer:', repr(self.peer), file=DEBUGSTREAM) self.push('220 %s %s' % (self.fqdn, __version__)) self.set_terminator(b'\r\n') # properties for backwards-compatibility