Python gevent 模块,socket() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用gevent.socket()

项目:deb-python-cassandra-driver    作者:openstack    | 项目源码 | 文件源码
def close(self):
        with self.lock:
            if self.is_closed:
                return
            self.is_closed = True

        log.debug("Closing connection (%s) to %s" % (id(self), self.host))
        if self._read_watcher:
            self._read_watcher.kill(block=False)
        if self._write_watcher:
            self._write_watcher.kill(block=False)
        if self._socket:
            self._socket.close()
        log.debug("Closed socket to %s" % (self.host,))

        if not self.is_defunct:
            self.error_all_requests(
                ConnectionShutdown("Connection to %s was closed" % self.host))
            # don't leave in-progress operations hanging
            self.connected_event.set()
项目:deb-python-cassandra-driver    作者:openstack    | 项目源码 | 文件源码
def handle_read(self):
        while True:
            try:
                buf = self._socket.recv(self.in_buffer_size)
                self._iobuf.write(buf)
            except socket.error as err:
                log.debug("Exception in read for %s: %s", self, err)
                self.defunct(err)
                return  # leave the read loop

            if buf and self._iobuf.tell():
                self.process_io_buffer()
            else:
                log.debug("Connection %s closed by server", self)
                self.close()
                return
项目:flasky    作者:RoseOu    | 项目源码 | 文件源码
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
项目:http_heartbeat_proxy    作者:purepy    | 项目源码 | 文件源码
def forward(source, dest, server):
    try:
        while True:
            try:
                data = source.recv(BUFFER_SIZE)
                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
项目:web_develop    作者:dongweiming    | 项目源码 | 文件源码
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
项目:chihu    作者:yelongyu    | 项目源码 | 文件源码
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
项目:ShelbySearch    作者:Agentscreech    | 项目源码 | 文件源码
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
项目:Price-Comparator    作者:Thejas-1    | 项目源码 | 文件源码
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
项目:tabmaster    作者:NicolasMinghetti    | 项目源码 | 文件源码
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
项目:YouPBX    作者:JoneXiong    | 项目源码 | 文件源码
def read_event(self):
        '''
        Reads one Event from socket until EOL.

        Returns Event instance.

        Raises LimitExceededError if MAXLINES_PER_EVENT is reached.
        '''
        buff = ''
        for x in range(MAXLINES_PER_EVENT):
            line = self.transport.read_line()
            if line == '':
                self.trace("no more data in read_event !")
                raise ConnectError("connection closed")
            elif line == EOL:
                # When matches EOL, creates Event and returns it.
                return Event(buff)
            else:
                # Else appends line to current buffer.
                buff = "%s%s" % (buff, line)
        raise LimitExceededError("max lines per event (%d) reached" % MAXLINES_PER_EVENT)
项目:infiblog    作者:RajuKoushik    | 项目源码 | 文件源码
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
项目:metrics    作者:Jeremy-Friedman    | 项目源码 | 文件源码
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
项目:metrics    作者:Jeremy-Friedman    | 项目源码 | 文件源码
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
项目:logo-gen    作者:jellene4eva    | 项目源码 | 文件源码
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
项目:liberator    作者:libscie    | 项目源码 | 文件源码
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
项目:mist.api    作者:mistio    | 项目源码 | 文件源码
def get_ssh_data(self):
        try:
            if self.provider == 'docker':
                try:
                    self.channel.send('\n')
                except:
                    pass
            while True:
                gevent.socket.wait_read(self.channel.fileno())
                try:
                    data = self.channel.recv(1024).decode('utf-8', 'ignore')
                except TypeError:
                    data = self.channel.recv().decode('utf-8', 'ignore')

                if not len(data):
                    return
                self.emit_shell_data(data)
        finally:
            self.channel.close()
项目:greenswitch    作者:EvoluxBR    | 项目源码 | 文件源码
def receive_events(self):
        buf = ''
        while self._run:
            try:
                data = self.sock_file.readline()
            except Exception:
                self._run = False
                self.connected = False
                self.sock.close()
                # logging.exception("Error reading from socket.")
                break
            if not data:
                if self.connected:
                    logging.error("Error receiving data, is FreeSWITCH running?")
                    self.connected = False
                break
            # Empty line
            if data == self._EOL:
                event = ESLEvent(buf)
                buf = ''
                self.handle_event(event)
                continue
            buf += data
项目:compatify    作者:hatooku    | 项目源码 | 文件源码
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
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
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
项目:deb-python-pymemcache    作者:openstack    | 项目源码 | 文件源码
def pytest_generate_tests(metafunc):
    if 'socket_module' in metafunc.fixturenames:
        socket_modules = [socket]
        try:
            from gevent import socket as gevent_socket
        except ImportError:
            print("Skipping gevent (not installed)")
        else:
            socket_modules.append(gevent_socket)

        metafunc.parametrize("socket_module", socket_modules)

    if 'client_class' in metafunc.fixturenames:
        from pymemcache.client.base import PooledClient, Client
        from pymemcache.client.hash import HashClient

        class HashClientSingle(HashClient):
            def __init__(self, server, *args, **kwargs):
                super(HashClientSingle, self).__init__(
                    [server], *args, **kwargs
                )

        metafunc.parametrize(
            "client_class", [Client, PooledClient, HashClientSingle]
        )
项目:ops_agent    作者:sjqzhang    | 项目源码 | 文件源码
def bind_unix_listener(self, path, backlog=50, user=None):
        try:
            sock = gevent.socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            sock.setblocking(0)
            self.unlink(path)
            sock.bind(path)
            if user is not None:
                import pwd
                user = pwd.getpwnam(user)
                os.chown(path, user.pw_uid, user.pw_gid)
            os.chmod(path, 0777)
            sock.listen(backlog)
        except Exception, e:
            self.logger.error("Create unix socket failed: %s", e.__str__())
            return None
        return sock
项目:Data-visualization    作者:insta-code1    | 项目源码 | 文件源码
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
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
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
项目:django-next-train    作者:bitpixdigital    | 项目源码 | 文件源码
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
项目:Lixiang_zhaoxin    作者:hejaxian    | 项目源码 | 文件源码
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
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
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
项目:python-dse-driver    作者:datastax    | 项目源码 | 文件源码
def close(self):
        with self.lock:
            if self.is_closed:
                return
            self.is_closed = True

        log.debug("Closing connection (%s) to %s" % (id(self), self.host))
        if self._read_watcher:
            self._read_watcher.kill(block=False)
        if self._write_watcher:
            self._write_watcher.kill(block=False)
        if self._socket:
            self._socket.close()
        log.debug("Closed socket to %s" % (self.host,))

        if not self.is_defunct:
            self.error_all_requests(
                ConnectionShutdown("Connection to %s was closed" % self.host))
            # don't leave in-progress operations hanging
            self.connected_event.set()
项目:python-dse-driver    作者:datastax    | 项目源码 | 文件源码
def handle_read(self):
        while True:
            try:
                buf = self._socket.recv(self.in_buffer_size)
                self._iobuf.write(buf)
            except socket.error as err:
                log.debug("Exception in read for %s: %s", self, err)
                self.defunct(err)
                return  # leave the read loop

            if buf and self._iobuf.tell():
                self.process_io_buffer()
            else:
                log.debug("Connection %s closed by server", self)
                self.close()
                return
项目:deb-python-cassandra-driver    作者:openstack    | 项目源码 | 文件源码
def handle_write(self):
        while True:
            try:
                next_msg = self._write_queue.get()
                self._socket.sendall(next_msg)
            except socket.error as err:
                log.debug("Exception in send for %s: %s", self, err)
                self.defunct(err)
                return
项目:Pyrlang    作者:esl    | 项目源码 | 文件源码
def _handle_socket_read(handler, sock):
    collected = b''
    while True:
        # a full packet before calling on_packet in the handler class
        ready = select.select([sock], [], [], 0.0)
        try:
            if ready[0]:
                data = sock.recv(4096)
                # print("data in: %s" % hex_bytes(data))

                collected += data

                # Try and consume repeatedly if multiple messages arrived
                # in the same packet
                while True:
                    collected1 = handler.consume(collected)
                    if collected1 is None:
                        print("Protocol requested to disconnect the socket")
                        break
                    if collected1 == collected:
                        break  # could not consume any more

                    collected = collected1
            else:
                handler.handle_inbox()

        except select.error:
            # Disconnected probably or another error
            break

    sock.close()
    handler.on_connection_lost()
项目:Pyrlang    作者:esl    | 项目源码 | 文件源码
def connect_with(protocol_class, host_port: tuple,
                 args: list, kwargs: dict):
    """ Helper which creates a new connection and feeds the data stream into
        a protocol handler class.

        :rtype: tuple(protocol_class, gevent.socket)
        :type protocol_class: class
        :param protocol_class: A handler class which has handler functions like
                on_connected, consume, and on_connection_lost
        :param kwargs: Keyword args to pass to the handler class constructor
        :param args: Args to pass to the handler class constructor
        :param host_port: (host,port) tuple where to connect
    """

    sock = socket.create_connection(address=host_port)

    handler = protocol_class(*args, **kwargs)
    handler.on_connected(sock, host_port)

    print("Connection to %s established" % str(host_port))

    try:
        g = gevent.spawn(_handle_socket_read, handler, sock)
        g.start()

    except Exception as e:
        print("\nException: %s" % e)
        traceback.print_exc()
        print()

    return handler, sock
项目:graphql-python-subscriptions    作者:hballard    | 项目源码 | 文件源码
def __init__(self, host='localhost', port=6379, *args, **kwargs):
        redis.connection.socket = gevent.socket
        self.redis = redis.StrictRedis(host, port, *args, **kwargs)
        self.pubsub = self.redis.pubsub()
        self.subscriptions = {}
        self.sub_id_counter = 0
        self.greenlet = None
项目:gipc    作者:jgehrcke    | 项目源码 | 文件源码
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
项目:gipc    作者:jgehrcke    | 项目源码 | 文件源码
def test_wsgi_scenario(self):
        from gevent.wsgi import WSGIServer

        def serve(http_server):
            http_server.serve_forever()

        def hello_world(environ, start_response):
            # Generate response in child process.
            with pipe() as (reader, writer):
                start_response('200 OK', [('Content-Type', 'text/html')])
                rg = start_process(
                    target=complchild_test_wsgi_scenario_respgen,
                    args=(writer, ))
                response = reader.get()
                rg.join()
                assert rg.exitcode == 0
            return [response]

        http_server = WSGIServer(('localhost', 0), hello_world)
        servelet = gevent.spawn(serve, http_server)
        # Wait for server being bound to socket.
        while True:
            if http_server.address[1] != 0:
                break
            gevent.sleep(0.05)
        client = start_process(
            target=complchild_test_wsgi_scenario_client,
            args=(http_server.address, ))
        client.join()
        assert client.exitcode == 0
        servelet.kill()
        servelet.get()  # get() is join and re-raises Exception.
项目:flasky    作者:RoseOu    | 项目源码 | 文件源码
def get_environ(self):
        env = super(PyWSGIHandler, self).get_environ()
        env['gunicorn.sock'] = self.socket
        env['RAW_URI'] = self.path
        return env
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def socket(self, *args, **kwargs):
        return utils.create_tcp_socket(socket)
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def create_connection(self, *args, **kwargs):
        return utils.create_tcp_connection(socket, *args, **kwargs)
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def create_socket_pair(self):
        return utils.create_socket_pair(socket)
项目:web_develop    作者:dongweiming    | 项目源码 | 文件源码
def close(self):
        if self.closed:
            sys.exit('Multiple exit signals received - aborting.')
        else:
            log('Closing listener socket')
            StreamServer.close(self)
项目:chihu    作者:yelongyu    | 项目源码 | 文件源码
def get_environ(self):
        env = super(PyWSGIHandler, self).get_environ()
        env['gunicorn.sock'] = self.socket
        env['RAW_URI'] = self.path
        return env
项目:ShelbySearch    作者:Agentscreech    | 项目源码 | 文件源码
def get_environ(self):
        env = super(PyWSGIHandler, self).get_environ()
        env['gunicorn.sock'] = self.socket
        env['RAW_URI'] = self.path
        return env
项目:Price-Comparator    作者:Thejas-1    | 项目源码 | 文件源码
def get_environ(self):
        env = super(PyWSGIHandler, self).get_environ()
        env['gunicorn.sock'] = self.socket
        env['RAW_URI'] = self.path
        return env
项目:tabmaster    作者:NicolasMinghetti    | 项目源码 | 文件源码
def get_environ(self):
        env = super(PyWSGIHandler, self).get_environ()
        env['gunicorn.sock'] = self.socket
        env['RAW_URI'] = self.path
        return env
项目:YouPBX    作者:JoneXiong    | 项目源码 | 文件源码
def handle_events(self):
        '''
        Gets and Dispatches events in an endless loop using gevent spawn.
        '''
        self.trace("handle_events started")
        while True:
            # Gets event and dispatches to handler.
            try:
                self.get_event()
                gevent.sleep(0)
                if not self.connected:
                    self.trace("Not connected !")
                    break
            except LimitExceededError:
                break
            except ConnectError:
                break
            except socket.error, se:
                break
            except GreenletExit, e:
                break
            except Exception, ex:
                self.trace("handle_events error => %s" % str(ex))
        self.trace("handle_events stopped now")

        try: 
            self.trace("handle_events socket.close")
            self.transport.sockfd.close()
            self.trace("handle_events socket.close success")
        except Exception, e:
            self.trace("handle_eventssocket.close ERROR: %s" % e)

        self.connected = False
        # prevent any pending request to be stuck
        self._flush_commands()
        return
项目:YouPBX    作者:JoneXiong    | 项目源码 | 文件源码
def disconnect(self):
        '''
        Disconnect and release socket and finally kill event handler.
        '''
        self.connected = False
        self.trace("releasing ...")
        try:
            # avoid handler stuck
            self._g_handler.get(block=True, timeout=2.0)
        except:
            self.trace("releasing forced")
            self._g_handler.kill()
        self.trace("releasing done")
        # prevent any pending request to be stuck
        self._flush_commands()
项目:infiblog    作者:RajuKoushik    | 项目源码 | 文件源码
def get_environ(self):
        env = super(PyWSGIHandler, self).get_environ()
        env['gunicorn.sock'] = self.socket
        env['RAW_URI'] = self.path
        return env
项目:tinybitcoinpeer    作者:amiller    | 项目源码 | 文件源码
def main():
    with contextlib.closing(socket.socket()) as s, \
         contextlib.closing(s.makefile('wb',0)) as writer, \
         contextlib.closing(s.makefile('rb', 0)) as reader:

        # This will actually return a random testnet node
        their_ip = socket.gethostbyname("testnet-seed.bitcoin.schildbach.de")
        print("Connecting to:", their_ip)

        my_ip = "127.0.0.1"

        s.connect( (their_ip,PORT) )
        stream = msg_stream(reader)

        # Send Version packet
        send(writer, version_pkt(my_ip, their_ip))

        # Receive their Version
        their_ver = next(stream)
        print('Received:', their_ver)

        # Send Version acknolwedgement (Verack)
        send(writer, msg_verack())

        # Fork off a handler, but keep a tee of the stream
        stream = tee_and_handle(writer, stream)

        # Get Verack
        their_verack = next(stream)

        # Send a ping!
        try:
            while True:
                send(writer, msg_ping())
                send(writer, msg_getaddr())
                gevent.sleep(5)
        except KeyboardInterrupt: pass
项目:lc_cloud    作者:refractionPOINT    | 项目源码 | 文件源码
def _connect( self ):
        try:
            self._socket = gevent.ssl.wrap_socket( gevent.socket.socket( gevent.socket.AF_INET, 
                                                                 gevent.socket.SOCK_STREAM ), 
                                           cert_reqs = gevent.ssl.CERT_NONE )
            self._socket.connect( ( self._destServer, self._destPort ) )
            self._log( "Connected" )
            headers = rSequence()
            headers.addSequence( Symbols.base.HCP_IDENT, AgentId( ( self._oid, self._iid, self._sid, self._plat, self._arch ) ).toJson() )
            headers.addStringA( Symbols.base.HOST_NAME, hashlib.md5( str( self._sid ) ).hexdigest() )
            headers.addIpv4( Symbols.base.IP_ADDRESS, "%d.%d.%d.%d" % ( random.randint( 0, 254 ), 
                                                                        random.randint( 0, 254 ), 
                                                                        random.randint( 0, 254 ), 
                                                                        random.randint( 0, 254 ) ) )
            if self._enrollmentToken is not None:
                headers.addBuffer( Symbols.hcp.ENROLLMENT_TOKEN, self._enrollmentToken )
            self._sendFrame( HcpModuleId.HCP, [ headers ], timeout = 30, isNotHbs = True )
            self._log( "Handshake sent" )
            self._threads.add( gevent.spawn( self._recvThread ) )
            self._threads.add( gevent.spawn_later( 1, self._syncHcpThread ) )
            self._threads.add( gevent.spawn_later( 10, self._syncHbsThread ) )
            self._threads.add( gevent.spawn_later( 2, lambda: self._connectedEvent.set() ) )
            return True
        except:
            self._log( "Failed to connect over TLS: %s" % traceback.format_exc() )
            return False
项目:lc_cloud    作者:refractionPOINT    | 项目源码 | 文件源码
def handle( self, source, address ):
        global currentEndpoints
        try:
            if 0 == len( currentEndpoints ): return

            print( "Connection from %s" % str( address ) )

            try:
                source.setsockopt( socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1 )
                source.setsockopt( socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 5 )
                source.setsockopt( socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 10 )
                source.setsockopt( socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 2 )
            except:
                print( "Failed to set keepalive on source connection" )

            try:
                dest = create_connection( random.sample( currentEndpoints, 1 )[ 0 ] )
            except:
                print( "Failed to connect to EndpointProcessor" )
            else:
                try:
                    try:
                        dest.setsockopt( socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1 )
                        dest.setsockopt( socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 5 )
                        dest.setsockopt( socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 10 )
                        dest.setsockopt( socket.IPPROTO_TCP, socket.TCP_KEEPCNT, 2 )
                    except:
                        print( "Failed to set keepalive on dest connection" )

                    # Send a small connection header that contains the original
                    # source of the connection.
                    connectionHeaders = msgpack.packb( address )
                    dest.sendall( struct.pack( '!I', len( connectionHeaders ) ) )
                    dest.sendall( connectionHeaders )

                    gevent.joinall( ( gevent.spawn( forward, source, dest, address, self ),
                                      gevent.spawn( forward, dest, source, address, self ) ) )
                finally:
                    dest.close()
        finally:
            source.close()
项目:metrics    作者:Jeremy-Friedman    | 项目源码 | 文件源码
def get_environ(self):
        env = super(PyWSGIHandler, self).get_environ()
        env['gunicorn.sock'] = self.socket
        env['RAW_URI'] = self.path
        return env