当前位置: 首页>>代码示例>>Python>>正文


Python socket.accept方法代码示例

本文整理汇总了Python中socket.accept方法的典型用法代码示例。如果您正苦于以下问题:Python socket.accept方法的具体用法?Python socket.accept怎么用?Python socket.accept使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在socket的用法示例。


在下文中一共展示了socket.accept方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: start_socket

# 需要导入模块: import socket [as 别名]
# 或者: from socket import accept [as 别名]
def start_socket(self, port=None):
        assert not hasattr(self, 'port'), 'Socket already initialized.'
        from _pydev_bundle.pydev_localhost import get_socket_name
        if SHOW_WRITES_AND_READS:
            print('start_socket')

        self._sequence = -1
        if port is None:
            socket_name = get_socket_name(close=True)
        else:
            socket_name = (pydev_localhost.get_localhost(), port)
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server_socket.bind(socket_name)
        self.port = socket_name[1]
        server_socket.listen(1)
        if SHOW_WRITES_AND_READS:
            print('Waiting in socket.accept()')
        self.server_socket = server_socket
        new_socket, addr = server_socket.accept()
        if SHOW_WRITES_AND_READS:
            print('Test Writer Thread Socket:', new_socket, addr)

        self._set_socket(new_socket) 
开发者ID:fabioz,项目名称:PyDev.Debugger,代码行数:26,代码来源:debugger_unittest.py

示例2: serve_forever

# 需要导入模块: import socket [as 别名]
# 或者: from socket import accept [as 别名]
def serve_forever(self, end=None):
        """
        end is an optional event to trigger server shutdown
        """
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.s.bind(('', self.port))
        self.s.listen(1)

        # because socket.accept is blocking we use select for its timeout
        # so every second we check if "forever" is over.
    
        while True:
            r, w, e = select.select((self.s,), (), (), 1)
            for l in r:
                t, address = self.s.accept()
                print("Accepting connection from {}:{}".format(*address))
                threading.Thread(target=self.handle_connection, args = (t, )).start()
            else:
                # should we quit?
                if end is not None and end.is_set():
                    return 
开发者ID:LinuxCircle,项目名称:tea5767,代码行数:25,代码来源:websocket-other.py

示例3: start_socket

# 需要导入模块: import socket [as 别名]
# 或者: from socket import accept [as 别名]
def start_socket(self):
        if SHOW_WRITES_AND_READS:
            print('start_socket')

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind(('', 0))
        self.port = s.getsockname()[1]
        s.listen(1)
        if SHOW_WRITES_AND_READS:
            print('Waiting in socket.accept()')
        newSock, addr = s.accept()
        if SHOW_WRITES_AND_READS:
            print('Test Writer Thread Socket:', newSock, addr)

        reader_thread = self.reader_thread = ReaderThread(newSock)
        reader_thread.start()
        self.sock = newSock

        self._sequence = -1
        # initial command is always the version
        self.write_version()
        self.log.append('start_socket') 
开发者ID:mrknow,项目名称:filmkodi,代码行数:24,代码来源:debugger_unittest.py

示例4: waitConnect

# 需要导入模块: import socket [as 别名]
# 或者: from socket import accept [as 别名]
def waitConnect():
    print("Server Video Generator wait client thread started")
    global connectedVideoGenerator
    while True:
        if connectedVideoGenerator is None:
            connection, address = socket.accept()
            print("%s Video Generator connected on %s" % (datetime.datetime.now(), address))
            connectedVideoGenerator = (connection, address)
            clientthread = Thread(target=videoGeneratorTick)
            clientthread.start() 
开发者ID:HA6Bots,项目名称:Automatic-Youtube-Reddit-Text-To-Speech-Video-Generator-and-Uploader,代码行数:12,代码来源:socketservervideogenerator.py

示例5: stop

# 需要导入模块: import socket [as 别名]
# 或者: from socket import accept [as 别名]
def stop(self):
        """Gracefully shutdown a server that is serving forever."""
        self.ready = False
        if self._start_time is not None:
            self._run_time += (time.time() - self._start_time)
        self._start_time = None
        
        sock = getattr(self, "socket", None)
        if sock:
            if not isinstance(self.bind_addr, basestring):
                # Touch our own socket to make accept() return immediately.
                try:
                    host, port = sock.getsockname()[:2]
                except socket.error, x:
                    if x.args[0] not in socket_errors_to_ignore:
                        # Changed to use error code and not message
                        # See http://www.cherrypy.org/ticket/860.
                        raise
                else:
                    # Note that we're explicitly NOT using AI_PASSIVE,
                    # here, because we want an actual IP to touch.
                    # localhost won't work if we've bound to a public IP,
                    # but it will if we bound to '0.0.0.0' (INADDR_ANY).
                    for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
                                                  socket.SOCK_STREAM):
                        af, socktype, proto, canonname, sa = res
                        s = None
                        try:
                            s = socket.socket(af, socktype, proto)
                            # See http://groups.google.com/group/cherrypy-users/
                            #        browse_frm/thread/bbfe5eb39c904fe0
                            s.settimeout(1.0)
                            s.connect((host, port))
                            s.close()
                        except socket.error:
                            if s:
                                s.close()
            if hasattr(sock, "close"):
                sock.close()
            self.socket = None 
开发者ID:joxeankoret,项目名称:nightmare,代码行数:42,代码来源:__init__.py

示例6: _accept_connection

# 需要导入模块: import socket [as 别名]
# 或者: from socket import accept [as 别名]
def _accept_connection(self, protocol_factory, sock,
                           sslcontext=None, server=None):
        try:
            conn, addr = sock.accept()
            if self._debug:
                logger.debug("%r got a new connection from %r: %r",
                             server, addr, conn)
            conn.setblocking(False)
        except (BlockingIOError, InterruptedError, ConnectionAbortedError):
            pass  # False alarm.
        except OSError as exc:
            # There's nowhere to send the error, so just log it.
            if exc.errno in (errno.EMFILE, errno.ENFILE,
                             errno.ENOBUFS, errno.ENOMEM):
                # Some platforms (e.g. Linux keep reporting the FD as
                # ready, so we remove the read handler temporarily.
                # We'll try again in a while.
                self.call_exception_handler({
                    'message': 'socket.accept() out of system resource',
                    'exception': exc,
                    'socket': sock,
                })
                self.remove_reader(sock.fileno())
                self.call_later(constants.ACCEPT_RETRY_DELAY,
                                self._start_serving,
                                protocol_factory, sock, sslcontext, server)
            else:
                raise  # The event loop will catch, log and ignore it.
        else:
            extra = {'peername': addr}
            accept = self._accept_connection2(protocol_factory, conn, extra,
                                              sslcontext, server)
            self.create_task(accept) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:35,代码来源:selector_events.py

示例7: _sock_accept

# 需要导入模块: import socket [as 别名]
# 或者: from socket import accept [as 别名]
def _sock_accept(self, fut, registered, sock):
        fd = sock.fileno()
        if registered:
            self.remove_reader(fd)
        if fut.cancelled():
            return
        try:
            conn, address = sock.accept()
            conn.setblocking(False)
        except (BlockingIOError, InterruptedError):
            self.add_reader(fd, self._sock_accept, fut, True, sock)
        except Exception as exc:
            fut.set_exception(exc)
        else:
            fut.set_result((conn, address)) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:17,代码来源:selector_events.py

示例8: pause_reading

# 需要导入模块: import socket [as 别名]
# 或者: from socket import accept [as 别名]
def pause_reading(self):
        # XXX This is a bit icky, given the comment at the top of
        # _read_ready().  Is it possible to evoke a deadlock?  I don't
        # know, although it doesn't look like it; write() will still
        # accept more data for the buffer and eventually the app will
        # call resume_reading() again, and things will flow again.

        if self._closing:
            raise RuntimeError('Cannot pause_reading() when closing')
        if self._paused:
            raise RuntimeError('Already paused')
        self._paused = True
        self._loop.remove_reader(self._sock_fd)
        if self._loop.get_debug():
            logger.debug("%r pauses reading", self) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:17,代码来源:selector_events.py

示例9: bind_and_listen_on_posix_socket

# 需要导入模块: import socket [as 别名]
# 或者: from socket import accept [as 别名]
def bind_and_listen_on_posix_socket(socket_name, accept_callback):
    """
    :param accept_callback: Called with `PosixSocketConnection` when a new
        connection is established.
    """
    assert socket_name is None or isinstance(socket_name, six.text_type)
    assert callable(accept_callback)

    # Py2 uses 0027 and Py3 uses 0o027, but both know
    # how to create the right value from the string '0027'.
    old_umask = os.umask(int('0027', 8))

    # Bind socket.
    socket_name, socket = _bind_posix_socket(socket_name)

    _ = os.umask(old_umask)

    # Listen on socket.
    socket.listen(0)

    def _accept_cb():
        connection, client_address = socket.accept()
        # Note: We don't have to put this socket in non blocking mode.
        #       This can cause crashes when sending big packets on OS X.

        posix_connection = PosixSocketConnection(connection)

        accept_callback(posix_connection)

    get_event_loop().add_reader(socket.fileno(), _accept_cb)

    logger.info('Listening on %r.' % socket_name)
    return socket_name 
开发者ID:prompt-toolkit,项目名称:pymux,代码行数:35,代码来源:posix.py

示例10: _accept_connection

# 需要导入模块: import socket [as 别名]
# 或者: from socket import accept [as 别名]
def _accept_connection(self, protocol_factory, sock,
                           sslcontext=None, server=None, backlog=100):
        # This method is only called once for each event loop tick where the
        # listening socket has triggered an EVENT_READ. There may be multiple
        # connections waiting for an .accept() so it is called in a loop.
        # See https://bugs.python.org/issue27906 for more details.
        for _ in range(backlog):
            try:
                conn, addr = sock.accept()
                if self._debug:
                    logger.debug("%r got a new connection from %r: %r",
                                 server, addr, conn)
                conn.setblocking(False)
            except (BlockingIOError, InterruptedError, ConnectionAbortedError):
                # Early exit because the socket accept buffer is empty.
                return None
            except OSError as exc:
                # There's nowhere to send the error, so just log it.
                if exc.errno in (errno.EMFILE, errno.ENFILE,
                                 errno.ENOBUFS, errno.ENOMEM):
                    # Some platforms (e.g. Linux keep reporting the FD as
                    # ready, so we remove the read handler temporarily.
                    # We'll try again in a while.
                    self.call_exception_handler({
                        'message': 'socket.accept() out of system resource',
                        'exception': exc,
                        'socket': sock,
                    })
                    self._remove_reader(sock.fileno())
                    self.call_later(constants.ACCEPT_RETRY_DELAY,
                                    self._start_serving,
                                    protocol_factory, sock, sslcontext, server,
                                    backlog)
                else:
                    raise  # The event loop will catch, log and ignore it.
            else:
                extra = {'peername': addr}
                accept = self._accept_connection2(protocol_factory, conn, extra,
                                                  sslcontext, server)
                self.create_task(accept) 
开发者ID:ShikyoKira,项目名称:Project-New-Reign---Nemesis-Main,代码行数:42,代码来源:selector_events.py

示例11: pause_reading

# 需要导入模块: import socket [as 别名]
# 或者: from socket import accept [as 别名]
def pause_reading(self):
        # XXX This is a bit icky, given the comment at the top of
        # _read_ready().  Is it possible to evoke a deadlock?  I don't
        # know, although it doesn't look like it; write() will still
        # accept more data for the buffer and eventually the app will
        # call resume_reading() again, and things will flow again.

        if self._closing:
            raise RuntimeError('Cannot pause_reading() when closing')
        if self._paused:
            raise RuntimeError('Already paused')
        self._paused = True
        self._loop._remove_reader(self._sock_fd)
        if self._loop.get_debug():
            logger.debug("%r pauses reading", self) 
开发者ID:ShikyoKira,项目名称:Project-New-Reign---Nemesis-Main,代码行数:17,代码来源:selector_events.py

示例12: accept

# 需要导入模块: import socket [as 别名]
# 或者: from socket import accept [as 别名]
def accept(self): 
		"""
		Frontend for socket.accept() method. Does exactly the same thing,
		except that returns an sctpsocket_tcp object instead of a standard
		Python socket. May throw the same exceptions as socket.accept()

		Returns: a sctpsocket_tcp() object
		"""
		sk, fromaddr = self._sk.accept()
		if sk:
			return (sctpsocket_tcp(self._family, sk), fromaddr)
		else:
			raise IOError("sctpsocket.accept() failed for unknown reason") 
开发者ID:yandex,项目名称:root-2015-tasks,代码行数:15,代码来源:sctp.py

示例13: stop

# 需要导入模块: import socket [as 别名]
# 或者: from socket import accept [as 别名]
def stop(self):
        """Gracefully shutdown a server that is serving forever."""
        self.ready = False
        if self._start_time is not None:
            self._run_time += (time.time() - self._start_time)
        self._start_time = None

        sock = getattr(self, "socket", None)
        if sock:
            if not isinstance(self.bind_addr, basestring):
                # Touch our own socket to make accept() return immediately.
                try:
                    host, port = sock.getsockname()[:2]
                except socket.error:
                    x = sys.exc_info()[1]
                    if x.args[0] not in socket_errors_to_ignore:
                        # Changed to use error code and not message
                        # See https://bitbucket.org/cherrypy/cherrypy/issue/860.
                        raise
                else:
                    # Note that we're explicitly NOT using AI_PASSIVE,
                    # here, because we want an actual IP to touch.
                    # localhost won't work if we've bound to a public IP,
                    # but it will if we bound to '0.0.0.0' (INADDR_ANY).
                    for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
                                                  socket.SOCK_STREAM):
                        af, socktype, proto, canonname, sa = res
                        s = None
                        try:
                            s = socket.socket(af, socktype, proto)
                            # See http://groups.google.com/group/cherrypy-users/
                            #        browse_frm/thread/bbfe5eb39c904fe0
                            s.settimeout(1.0)
                            s.connect((host, port))
                            s.close()
                        except socket.error:
                            if s:
                                s.close()
            if hasattr(sock, "close"):
                sock.close()
            self.socket = None

        self.requests.stop(self.shutdown_timeout) 
开发者ID:exiahuang,项目名称:SalesforceXyTools,代码行数:45,代码来源:wsgiserver3.py

示例14: tick

# 需要导入模块: import socket [as 别名]
# 或者: from socket import accept [as 别名]
def tick(self):
        """Accept a new connection and put it on the Queue."""
        try:
            s, addr = self.socket.accept()
            if self.stats['Enabled']:
                self.stats['Accepts'] += 1
            if not self.ready:
                return
            
            prevent_socket_inheritance(s)
            if hasattr(s, 'settimeout'):
                s.settimeout(self.timeout)
            
            makefile = CP_fileobject
            ssl_env = {}
            # if ssl cert and key are set, we try to be a secure HTTP server
            if self.ssl_adapter is not None:
                try:
                    s, ssl_env = self.ssl_adapter.wrap(s)
                except NoSSLError:
                    msg = ("The client sent a plain HTTP request, but "
                           "this server only speaks HTTPS on this port.")
                    buf = ["%s 400 Bad Request\r\n" % self.protocol,
                           "Content-Length: %s\r\n" % len(msg),
                           "Content-Type: text/plain\r\n\r\n",
                           msg]
                    
                    wfile = CP_fileobject(s, "wb", DEFAULT_BUFFER_SIZE)
                    try:
                        wfile.sendall("".join(buf))
                    except socket.error, x:
                        if x.args[0] not in socket_errors_to_ignore:
                            raise
                    return
                if not s:
                    return
                makefile = self.ssl_adapter.makefile
                # Re-apply our timeout since we may have a new socket object
                if hasattr(s, 'settimeout'):
                    s.settimeout(self.timeout)
            
            conn = self.ConnectionClass(self, s, makefile)
            
            if not isinstance(self.bind_addr, basestring):
                # optional values
                # Until we do DNS lookups, omit REMOTE_HOST
                if addr is None: # sometimes this can happen
                    # figure out if AF_INET or AF_INET6.
                    if len(s.getsockname()) == 2:
                        # AF_INET
                        addr = ('0.0.0.0', 0)
                    else:
                        # AF_INET6
                        addr = ('::', 0)
                conn.remote_addr = addr[0]
                conn.remote_port = addr[1]
            
            conn.ssl_env = ssl_env
            
            self.requests.put(conn) 
开发者ID:joxeankoret,项目名称:nightmare,代码行数:62,代码来源:__init__.py

示例15: stop

# 需要导入模块: import socket [as 别名]
# 或者: from socket import accept [as 别名]
def stop(self):
        """Gracefully shutdown a server that is serving forever."""
        self.ready = False
        if self._start_time is not None:
            self._run_time += (time.time() - self._start_time)
        self._start_time = None

        sock = getattr(self, "socket", None)
        if sock:
            if not isinstance(self.bind_addr, basestring):
                # Touch our own socket to make accept() return immediately.
                try:
                    host, port = sock.getsockname()[:2]
                except socket.error:
                    x = sys.exc_info()[1]
                    if x.args[0] not in socket_errors_to_ignore:
                        # Changed to use error code and not message
                        # See
                        # https://github.com/cherrypy/cherrypy/issues/860.
                        raise
                else:
                    # Note that we're explicitly NOT using AI_PASSIVE,
                    # here, because we want an actual IP to touch.
                    # localhost won't work if we've bound to a public IP,
                    # but it will if we bound to '0.0.0.0' (INADDR_ANY).
                    for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
                                                  socket.SOCK_STREAM):
                        af, socktype, proto, canonname, sa = res
                        s = None
                        try:
                            s = socket.socket(af, socktype, proto)
                            # See
                            # http://groups.google.com/group/cherrypy-users/
                            #     browse_frm/thread/bbfe5eb39c904fe0
                            s.settimeout(1.0)
                            s.connect((host, port))
                            s.close()
                        except socket.error:
                            if s:
                                s.close()
            if hasattr(sock, "close"):
                sock.close()
            self.socket = None

        self.requests.stop(self.shutdown_timeout) 
开发者ID:Naayouu,项目名称:Hatkey,代码行数:47,代码来源:wsgiserver3.py


注:本文中的socket.accept方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。