當前位置: 首頁>>代碼示例>>Python>>正文


Python gevent.socket方法代碼示例

本文整理匯總了Python中gevent.socket方法的典型用法代碼示例。如果您正苦於以下問題:Python gevent.socket方法的具體用法?Python gevent.socket怎麽用?Python gevent.socket使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在gevent的用法示例。


在下文中一共展示了gevent.socket方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: patch

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import socket [as 別名]
def patch(self):
        from gevent import monkey
        monkey.noisy = False

        # if the new version is used make sure to patch subprocess
        if gevent.version_info[0] == 0:
            monkey.patch_all()
        else:
            monkey.patch_all(subprocess=True)

        # monkey patch sendfile to make it none blocking
        patch_sendfile()

        # patch sockets
        sockets = []
        for s in self.sockets:
            if sys.version_info[0] == 3:
                sockets.append(socket(s.FAMILY, _socket.SOCK_STREAM,
                    fileno=s.sock.fileno()))
            else:
                sockets.append(socket(s.FAMILY, _socket.SOCK_STREAM,
                    _sock=s))
        self.sockets = sockets 
開發者ID:jpush,項目名稱:jbox,代碼行數:25,代碼來源:ggevent.py

示例2: create_actor_pool

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import socket [as 別名]
def create_actor_pool(*args, **kwargs):
    import gevent.socket

    address = kwargs.pop('address', None)
    if not address:
        return new_actor_pool(*args, **kwargs)

    if isinstance(address, str):
        port = int(address.rsplit(':', 1)[1])
    else:
        port = DEFAULT_PORT
    it = itertools.count(port)

    auto_port = kwargs.pop('auto_port', True)
    while True:
        try:
            address = '127.0.0.1:{0}'.format(next(it))
            return new_actor_pool(address, *args, **kwargs)
        except gevent.socket.error:
            if auto_port:
                continue
            raise 
開發者ID:mars-project,項目名稱:mars,代碼行數:24,代碼來源:test_gevent_pool.py

示例3: bootstrap_from_dns

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import socket [as 別名]
def bootstrap_from_dns(self):
        """
        Fetches CM server list from WebAPI and replaces the current one
        """
        self._LOG.debug("Attempting bootstrap via DNS")

        try:
            answer = socket.getaddrinfo("cm0.steampowered.com",
                                        27017,
                                        socket.AF_INET,
                                        proto=socket.IPPROTO_TCP)
        except Exception as exp:
            self._LOG.error("DNS boostrap failed: %s" % str(exp))
            return False

        servers = list(map(lambda addr: addr[4], answer))

        if servers:
            self.clear()
            self.merge_list(servers)
            return True
        else:
            self._LOG.error("DNS boostrap: cm0.steampowered.com resolved no A records")
            return False 
開發者ID:ValvePython,項目名稱:steam,代碼行數:26,代碼來源:cm.py

示例4: __init__

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import socket [as 別名]
def __init__(self,
                 zmq_context,
                 zmq_proxy_xsub_url=ait.SERVER_DEFAULT_XSUB_URL,
                 zmq_proxy_xpub_url=ait.SERVER_DEFAULT_XPUB_URL,
                 **kwargs):

        if 'input' in kwargs and type(kwargs['input'][0]) is int:
            super(PortInputClient, self).__init__(zmq_context,
                                                  zmq_proxy_xsub_url,
                                                  zmq_proxy_xpub_url,
                                                  listener=int(kwargs['input'][0]))
        else:
            raise(ValueError('Input must be port in order to create PortInputClient'))

        # open sub socket
        self.sub = gevent.socket.socket(gevent.socket.AF_INET, gevent.socket.SOCK_DGRAM) 
開發者ID:NASA-AMMOS,項目名稱:AIT-Core,代碼行數:18,代碼來源:client.py

示例5: test_mocked_eth_socket

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import socket [as 別名]
def test_mocked_eth_socket(self, socket_mock):
        socket_family = getattr(gevent.socket,
                                'AF_PACKET',
                                gevent.socket.AF_INET)
        proto = bsc.ETH_PROTOCOL
        handler = {'name':'name', 'log_dir':'/tmp'}
        bsc.RAW_SOCKET_FD = 'foobar'
        sl = bsc.SocketStreamCapturer([handler], ['eho0', 0], 'ethernet')
        # We need to test a different load if the rawsocket package is used
        if not bsc.RAW_SOCKET_FD:
            socket_mock.socket.assert_called_with(socket_family,
                                                  gevent.socket.SOCK_RAW,
                                                  socket.htons(proto))
        else:
            socket_mock.fromfd.assert_called_with(bsc.RAW_SOCKET_FD,
                                                  socket_family,
                                                  gevent.socket.SOCK_RAW,
                                                  socket.htons(proto))
        assert sl.conn_type == 'ethernet'
        bsc.RAW_SOCKET_FD = None 
開發者ID:NASA-AMMOS,項目名稱:AIT-Core,代碼行數:22,代碼來源:test_bsc.py

示例6: test_mocked_eth_socket_with_rawsocket

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import socket [as 別名]
def test_mocked_eth_socket_with_rawsocket(self, socket_mock):
        socket_family = getattr(gevent.socket,
                                'AF_PACKET',
                                gevent.socket.AF_INET)

        rawsocket_is_installed = True if bsc.RAW_SOCKET_FD else False
        if not rawsocket_is_installed:
            rawsocket_fd = 'fake_rawsocket_fd'
            bsc.RAW_SOCKET_FD = rawsocket_fd
        else:
            rawsocket_fd = bsc.RAW_SOCKET_FD

        handler = {'name':'name', 'log_dir':'/tmp'}
        sl = bsc.SocketStreamCapturer([handler], ['eho0', 0], 'ethernet')
        # We need to test a different load if the rawsocket package is used
        socket_mock.fromfd.assert_called_with(rawsocket_fd,
                                              socket_family,
                                              gevent.socket.SOCK_RAW,
                                              socket.htons(bsc.ETH_PROTOCOL))
        assert sl.conn_type == 'ethernet'

        if not rawsocket_is_installed:
            bsc.RAW_SOCKET_FD = None 
開發者ID:NASA-AMMOS,項目名稱:AIT-Core,代碼行數:25,代碼來源:test_bsc.py

示例7: connect

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import socket [as 別名]
def connect(self, address, remote_pubkey):
        log.debug('connecting', address=address)
        """
        gevent.socket.create_connection(address, timeout=Timeout, source_address=None)
        Connect to address (a 2-tuple (host, port)) and return the socket object.
        Passing the optional timeout parameter will set the timeout
        getdefaulttimeout() is default
        """
        try:
            connection = create_connection(address, timeout=self.connect_timeout)
        except socket.timeout:
            log.info('connection timeout', address=address, timeout=self.connect_timeout)
            self.errors.add(address, 'connection timeout')
            return False
        except socket.error as e:
            log.info('connection error', errno=e.errno, reason=e.strerror)
            self.errors.add(address, 'connection error')
            return False
        self._start_peer(connection, address, remote_pubkey)
        return True 
開發者ID:heikoheiko,項目名稱:pydevp2p,代碼行數:22,代碼來源:peermanager.py

示例8: run_query

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import socket [as 別名]
def run_query(self, query, noreply):
        self._write_mutex.acquire()

        try:
            self._socket.sendall(query.serialize(self._parent._get_json_encoder(query)))
        finally:
            self._write_mutex.release()

        if noreply:
            return None

        async_res = AsyncResult()
        self._user_queries[query.token] = (query, async_res)
        return async_res.get()

    # The _reader coroutine runs in its own coroutine in parallel, reading responses
    # off of the socket and forwarding them to the appropriate AsyncResult or Cursor.
    # This is shut down as a consequence of closing the stream, or an error in the
    # socket/protocol from the server.  Unexpected errors in this coroutine will
    # close the ConnectionInstance and be passed to any open AsyncResult or Cursors. 
開發者ID:rethinkdb,項目名稱:rethinkdb-python,代碼行數:22,代碼來源:net_gevent.py

示例9: patch

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import socket [as 別名]
def patch(self):
        from gevent import monkey
        monkey.noisy = False

        # if the new version is used make sure to patch subprocess
        if gevent.version_info[0] == 0:
            monkey.patch_all()
        else:
            monkey.patch_all(subprocess=True)

        # monkey patch sendfile to make it none blocking
        patch_sendfile()

        # patch sockets
        sockets = []
        for s in self.sockets:
            sockets.append(socket(s.FAMILY, _socket.SOCK_STREAM,
                _sock=s))
        self.sockets = sockets 
開發者ID:chalasr,項目名稱:Flask-P2P,代碼行數:21,代碼來源:ggevent.py

示例10: forward

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import socket [as 別名]
def forward(source, dest, server):
    source_address = '%s:%s' % source.getpeername()[:2]
    dest_address = '%s:%s' % dest.getpeername()[:2]
    try:
        while True:
            try:
                data = source.recv(1024)
                log('%s->%s', source_address, dest_address)
                if not data:
                    break
                dest.sendall(data)
            except KeyboardInterrupt:
                if not server.closed:
                    server.close()
                break
            except socket.error:
                if not server.closed:
                    server.close()
                break
    finally:
        source.close()
        dest.close()
        server = None 
開發者ID:dongweiming,項目名稱:web_develop,代碼行數:25,代碼來源:portforwarder.py

示例11: test_getaddrinfo_mp

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import socket [as 別名]
def test_getaddrinfo_mp(self):
        """This test would make gevent's hub threadpool kill upon hub
        destruction in child block forever. Gipc resolves this by killing
        threadpool even harder.
        """
        import gevent.socket as socket
        socket.getaddrinfo("localhost", 21)
        p = start_process(target=complchild_test_getaddrinfo_mp)
        p.join(timeout=1)
        assert p.exitcode == 0 
開發者ID:jgehrcke,項目名稱:gipc,代碼行數:12,代碼來源:test_gipc.py

示例12: get_environ

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import socket [as 別名]
def get_environ(self):
        env = super(PyWSGIHandler, self).get_environ()
        env['gunicorn.sock'] = self.socket
        env['RAW_URI'] = self.path
        return env 
開發者ID:jpush,項目名稱:jbox,代碼行數:7,代碼來源:ggevent.py

示例13: capture_packet

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import socket [as 別名]
def capture_packet(self):
        ''' Write packet data to the logger's log file. '''
        data = self.socket.recv(self._buffer_size)

        for h in self.capture_handlers:
            h['reads'] += 1
            h['data_read'] += len(data)

            d = data
            if 'pre_write_transforms' in h:
                for data_transform in h['pre_write_transforms']:
                    d = data_transform(d)
            h['logger'].write(d) 
開發者ID:NASA-AMMOS,項目名稱:AIT-Core,代碼行數:15,代碼來源:bsc.py

示例14: socket_monitor_loop

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import socket [as 別名]
def socket_monitor_loop(self):
        ''' Monitor the socket and log captured data. '''
        try:
            while True:
                gevent.socket.wait_read(self.socket.fileno())

                self._handle_log_rotations()
                self.capture_packet()
        finally:
            self.clean_up() 
開發者ID:NASA-AMMOS,項目名稱:AIT-Core,代碼行數:12,代碼來源:bsc.py

示例15: _add_logger_by_name

# 需要導入模塊: import gevent [as 別名]
# 或者: from gevent import socket [as 別名]
def _add_logger_by_name(self, name):
        ''' Handles POST requests for adding a new logger.

        Expects logger configuration to be passed in the request's query string.
        The logger name is included in the URL and the address components and
        connection type should be included as well. The loc attribute is
        defaulted to "localhost" when making the socket connection if not
        defined.

        loc = IP / interface
        port = port / protocol
        conn_type = udp or ethernet

        Raises:
            ValueError:
                if the port or connection type are not supplied.
        '''
        data = dict(request.forms)
        loc = data.pop('loc', '')
        port = data.pop('port', None)
        conn_type = data.pop('conn_type', None)

        if not port or not conn_type:
            e = 'Port and/or conn_type not set'
            raise ValueError(e)
        address = [loc, int(port)]

        if 'rotate_log' in data:
            data['rotate_log'] = True if data == 'true' else False

        if 'rotate_log_delta' in data:
            data['rotate_log_delta'] = int(data['rotate_log_delta'])

        self._logger_manager.add_logger(name, address, conn_type, **data) 
開發者ID:NASA-AMMOS,項目名稱:AIT-Core,代碼行數:36,代碼來源:bsc.py


注:本文中的gevent.socket方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。