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


Python tcpclient.TCPClient方法代碼示例

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


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

示例1: start

# 需要導入模塊: from tornado import tcpclient [as 別名]
# 或者: from tornado.tcpclient import TCPClient [as 別名]
def start(self):
        wait_sec = 10
        while True:
            try:
                self.stream = yield TCPClient().connect(self.host, self.port)
                break
            except iostream.StreamClosedError:
                logger.error("connect error and again")
                yield gen.sleep(wait_sec)
                wait_sec = (wait_sec if (wait_sec >= 60) else (wait_sec * 2))
            
        self.send_heart_beat()
        self.heartbeat_callback = PeriodicCallback(self.send_heart_beat, 1000 * HEARTBEAT_TIMEOUT)
        self.heartbeat_callback.start()                 # start scheduler
        self.login()
        self.stream.read_bytes(16, self.__recv_header) 
開發者ID:wechat-tests,項目名稱:PyMicroChat,代碼行數:18,代碼來源:client_tornado.py

示例2: __init__

# 需要導入模塊: from tornado import tcpclient [as 別名]
# 或者: from tornado.tcpclient import TCPClient [as 別名]
def __init__(self,
                 host,
                 port,
                 db,
                 on_written,
                 on_close,
                 io_loop,
                 cluster_node=False,
                 read_only=False,
                 slots=None):
        super(_Connection, self).__init__()
        self.connected = False
        self.io_loop = io_loop
        self.host = host
        self.port = port
        self.database = int(db or DEFAULT_DB)

        self._client = tcpclient.TCPClient()
        self._cluster_node = cluster_node
        self._read_only = read_only
        self._slots = slots or []
        self._stream = None
        self._on_connect = None
        self._on_close = on_close
        self._on_written = on_written 
開發者ID:gmr,項目名稱:tredis,代碼行數:27,代碼來源:client.py

示例3: __init__

# 需要導入模塊: from tornado import tcpclient [as 別名]
# 或者: from tornado.tcpclient import TCPClient [as 別名]
def __init__(self, request, on_message_callback=None,
                 compression_options=None, ping_interval=None, ping_timeout=None,
                 max_message_size=None, subprotocols=[]):
        self.compression_options = compression_options
        self.connect_future = Future()
        self.protocol = None
        self.read_queue = Queue(1)
        self.key = base64.b64encode(os.urandom(16))
        self._on_message_callback = on_message_callback
        self.close_code = self.close_reason = None
        self.ping_interval = ping_interval
        self.ping_timeout = ping_timeout
        self.max_message_size = max_message_size

        scheme, sep, rest = request.url.partition(':')
        scheme = {'ws': 'http', 'wss': 'https'}[scheme]
        request.url = scheme + sep + rest
        request.headers.update({
            'Upgrade': 'websocket',
            'Connection': 'Upgrade',
            'Sec-WebSocket-Key': self.key,
            'Sec-WebSocket-Version': '13',
        })
        if subprotocols is not None:
            request.headers['Sec-WebSocket-Protocol'] = ','.join(subprotocols)
        if self.compression_options is not None:
            # Always offer to let the server set our max_wbits (and even though
            # we don't offer it, we will accept a client_no_context_takeover
            # from the server).
            # TODO: set server parameters for deflate extension
            # if requested in self.compression_options.
            request.headers['Sec-WebSocket-Extensions'] = (
                'permessage-deflate; client_max_window_bits')

        self.tcp_client = TCPClient()
        super(WebSocketClientConnection, self).__init__(
            None, request, lambda: None, self._on_http_response,
            104857600, self.tcp_client, 65536, 104857600) 
開發者ID:tp4a,項目名稱:teleport,代碼行數:40,代碼來源:websocket.py

示例4: __init__

# 需要導入模塊: from tornado import tcpclient [as 別名]
# 或者: from tornado.tcpclient import TCPClient [as 別名]
def __init__(self, io_loop, request, on_message_callback=None,
                 compression_options=None):
        self.compression_options = compression_options
        self.connect_future = TracebackFuture()
        self.protocol = None
        self.read_future = None
        self.read_queue = collections.deque()
        self.key = base64.b64encode(os.urandom(16))
        self._on_message_callback = on_message_callback
        self.close_code = self.close_reason = None

        scheme, sep, rest = request.url.partition(':')
        scheme = {'ws': 'http', 'wss': 'https'}[scheme]
        request.url = scheme + sep + rest
        request.headers.update({
            'Upgrade': 'websocket',
            'Connection': 'Upgrade',
            'Sec-WebSocket-Key': self.key,
            'Sec-WebSocket-Version': '13',
        })
        if self.compression_options is not None:
            # Always offer to let the server set our max_wbits (and even though
            # we don't offer it, we will accept a client_no_context_takeover
            # from the server).
            # TODO: set server parameters for deflate extension
            # if requested in self.compression_options.
            request.headers['Sec-WebSocket-Extensions'] = (
                'permessage-deflate; client_max_window_bits')

        self.tcp_client = TCPClient(io_loop=io_loop)
        super(WebSocketClientConnection, self).__init__(
            io_loop, None, request, lambda: None, self._on_http_response,
            104857600, self.tcp_client, 65536, 104857600) 
開發者ID:tao12345666333,項目名稱:tornado-zh,代碼行數:35,代碼來源:websocket.py

示例5: setUp

# 需要導入模塊: from tornado import tcpclient [as 別名]
# 或者: from tornado.tcpclient import TCPClient [as 別名]
def setUp(self):
        super(TCPClientTest, self).setUp()
        self.server = None
        self.client = TCPClient() 
開發者ID:tao12345666333,項目名稱:tornado-zh,代碼行數:6,代碼來源:tcpclient_test.py

示例6: __init__

# 需要導入模塊: from tornado import tcpclient [as 別名]
# 或者: from tornado.tcpclient import TCPClient [as 別名]
def __init__(
        self,
        client: Optional[SimpleAsyncHTTPClient],
        request: HTTPRequest,
        release_callback: Callable[[], None],
        final_callback: Callable[[HTTPResponse], None],
        max_buffer_size: int,
        tcp_client: TCPClient,
        max_header_size: int,
        max_body_size: int,
    ) -> None:
        self.io_loop = IOLoop.current()
        self.start_time = self.io_loop.time()
        self.start_wall_time = time.time()
        self.client = client
        self.request = request
        self.release_callback = release_callback
        self.final_callback = final_callback
        self.max_buffer_size = max_buffer_size
        self.tcp_client = tcp_client
        self.max_header_size = max_header_size
        self.max_body_size = max_body_size
        self.code = None  # type: Optional[int]
        self.headers = None  # type: Optional[httputil.HTTPHeaders]
        self.chunks = []  # type: List[bytes]
        self._decompressor = None
        # Timeout handle returned by IOLoop.add_timeout
        self._timeout = None  # type: object
        self._sockaddr = None
        IOLoop.current().add_future(
            gen.convert_yielded(self.run()), lambda f: f.result()
        ) 
開發者ID:opendevops-cn,項目名稱:opendevops,代碼行數:34,代碼來源:simple_httpclient.py

示例7: test_connect_timeout

# 需要導入模塊: from tornado import tcpclient [as 別名]
# 或者: from tornado.tcpclient import TCPClient [as 別名]
def test_connect_timeout(self):
        timeout = 0.05

        class TimeoutResolver(Resolver):
            def resolve(self, *args, **kwargs):
                return Future()  # never completes

        with self.assertRaises(TimeoutError):
            yield TCPClient(resolver=TimeoutResolver()).connect(
                "1.2.3.4", 12345, timeout=timeout
            ) 
開發者ID:opendevops-cn,項目名稱:opendevops,代碼行數:13,代碼來源:tcpclient_test.py

示例8: test_connect_timeout

# 需要導入模塊: from tornado import tcpclient [as 別名]
# 或者: from tornado.tcpclient import TCPClient [as 別名]
def test_connect_timeout(self):
        timeout = 0.05

        class TimeoutResolver(Resolver):
            def resolve(self, *args, **kwargs):
                return Future()  # never completes
        with self.assertRaises(TimeoutError):
            yield TCPClient(resolver=TimeoutResolver()).connect(
                '1.2.3.4', 12345, timeout=timeout) 
開發者ID:tp4a,項目名稱:teleport,代碼行數:11,代碼來源:tcpclient_test.py

示例9: connect

# 需要導入模塊: from tornado import tcpclient [as 別名]
# 或者: from tornado.tcpclient import TCPClient [as 別名]
def connect(self):
        adb_host = self.__host or os.environ.get(
            "ANDROID_ADB_SERVER_HOST", "127.0.0.1")
        adb_port = self.__port or int(os.environ.get(
            "ANDROID_ADB_SERVER_PORT", 5037))
        stream = await TCPClient().connect(adb_host, adb_port)
        self.__stream = stream
        return self 
開發者ID:openatx,項目名稱:atxserver2-android-provider,代碼行數:10,代碼來源:asyncadb.py

示例10: initialize

# 需要導入模塊: from tornado import tcpclient [as 別名]
# 或者: from tornado.tcpclient import TCPClient [as 別名]
def initialize(self, io_loop, max_clients=10,
                   hostname_mapping=None, max_buffer_size=104857600,
                   resolver=None, defaults=None, max_header_size=None,
                   max_body_size=None):
        """Creates a AsyncHTTPClient.

        Only a single AsyncHTTPClient instance exists per IOLoop
        in order to provide limitations on the number of pending connections.
        ``force_instance=True`` may be used to suppress this behavior.

        Note that because of this implicit reuse, unless ``force_instance``
        is used, only the first call to the constructor actually uses
        its arguments. It is recommended to use the ``configure`` method
        instead of the constructor to ensure that arguments take effect.

        ``max_clients`` is the number of concurrent requests that can be
        in progress; when this limit is reached additional requests will be
        queued. Note that time spent waiting in this queue still counts
        against the ``request_timeout``.

        ``hostname_mapping`` is a dictionary mapping hostnames to IP addresses.
        It can be used to make local DNS changes when modifying system-wide
        settings like ``/etc/hosts`` is not possible or desirable (e.g. in
        unittests).

        ``max_buffer_size`` (default 100MB) is the number of bytes
        that can be read into memory at once. ``max_body_size``
        (defaults to ``max_buffer_size``) is the largest response body
        that the client will accept.  Without a
        ``streaming_callback``, the smaller of these two limits
        applies; with a ``streaming_callback`` only ``max_body_size``
        does.

        .. versionchanged:: 4.2
           Added the ``max_body_size`` argument.
        """
        super(SimpleAsyncHTTPClient, self).initialize(io_loop,
                                                      defaults=defaults)
        self.max_clients = max_clients
        self.queue = collections.deque()
        self.active = {}
        self.waiting = {}
        self.max_buffer_size = max_buffer_size
        self.max_header_size = max_header_size
        self.max_body_size = max_body_size
        # TCPClient could create a Resolver for us, but we have to do it
        # ourselves to support hostname_mapping.
        if resolver:
            self.resolver = resolver
            self.own_resolver = False
        else:
            self.resolver = Resolver(io_loop=io_loop)
            self.own_resolver = True
        if hostname_mapping is not None:
            self.resolver = OverrideResolver(resolver=self.resolver,
                                             mapping=hostname_mapping)
        self.tcp_client = TCPClient(resolver=self.resolver, io_loop=io_loop) 
開發者ID:tao12345666333,項目名稱:tornado-zh,代碼行數:59,代碼來源:simple_httpclient.py

示例11: __init__

# 需要導入模塊: from tornado import tcpclient [as 別名]
# 或者: from tornado.tcpclient import TCPClient [as 別名]
def __init__(
        self,
        request: httpclient.HTTPRequest,
        on_message_callback: Callable[[Union[None, str, bytes]], None] = None,
        compression_options: Dict[str, Any] = None,
        ping_interval: float = None,
        ping_timeout: float = None,
        max_message_size: int = _default_max_message_size,
        subprotocols: Optional[List[str]] = [],
    ) -> None:
        self.connect_future = Future()  # type: Future[WebSocketClientConnection]
        self.read_queue = Queue(1)  # type: Queue[Union[None, str, bytes]]
        self.key = base64.b64encode(os.urandom(16))
        self._on_message_callback = on_message_callback
        self.close_code = None  # type: Optional[int]
        self.close_reason = None  # type: Optional[str]
        self.params = _WebSocketParams(
            ping_interval=ping_interval,
            ping_timeout=ping_timeout,
            max_message_size=max_message_size,
            compression_options=compression_options,
        )

        scheme, sep, rest = request.url.partition(":")
        scheme = {"ws": "http", "wss": "https"}[scheme]
        request.url = scheme + sep + rest
        request.headers.update(
            {
                "Upgrade": "websocket",
                "Connection": "Upgrade",
                "Sec-WebSocket-Key": self.key,
                "Sec-WebSocket-Version": "13",
            }
        )
        if subprotocols is not None:
            request.headers["Sec-WebSocket-Protocol"] = ",".join(subprotocols)
        if compression_options is not None:
            # Always offer to let the server set our max_wbits (and even though
            # we don't offer it, we will accept a client_no_context_takeover
            # from the server).
            # TODO: set server parameters for deflate extension
            # if requested in self.compression_options.
            request.headers[
                "Sec-WebSocket-Extensions"
            ] = "permessage-deflate; client_max_window_bits"

        self.tcp_client = TCPClient()
        super(WebSocketClientConnection, self).__init__(
            None,
            request,
            lambda: None,
            self._on_http_response,
            104857600,
            self.tcp_client,
            65536,
            104857600,
        ) 
開發者ID:opendevops-cn,項目名稱:opendevops,代碼行數:59,代碼來源:websocket.py

示例12: initialize

# 需要導入模塊: from tornado import tcpclient [as 別名]
# 或者: from tornado.tcpclient import TCPClient [as 別名]
def initialize(self, max_clients=10,
                   hostname_mapping=None, max_buffer_size=104857600,
                   resolver=None, defaults=None, max_header_size=None,
                   max_body_size=None):
        """Creates a AsyncHTTPClient.

        Only a single AsyncHTTPClient instance exists per IOLoop
        in order to provide limitations on the number of pending connections.
        ``force_instance=True`` may be used to suppress this behavior.

        Note that because of this implicit reuse, unless ``force_instance``
        is used, only the first call to the constructor actually uses
        its arguments. It is recommended to use the ``configure`` method
        instead of the constructor to ensure that arguments take effect.

        ``max_clients`` is the number of concurrent requests that can be
        in progress; when this limit is reached additional requests will be
        queued. Note that time spent waiting in this queue still counts
        against the ``request_timeout``.

        ``hostname_mapping`` is a dictionary mapping hostnames to IP addresses.
        It can be used to make local DNS changes when modifying system-wide
        settings like ``/etc/hosts`` is not possible or desirable (e.g. in
        unittests).

        ``max_buffer_size`` (default 100MB) is the number of bytes
        that can be read into memory at once. ``max_body_size``
        (defaults to ``max_buffer_size``) is the largest response body
        that the client will accept.  Without a
        ``streaming_callback``, the smaller of these two limits
        applies; with a ``streaming_callback`` only ``max_body_size``
        does.

        .. versionchanged:: 4.2
           Added the ``max_body_size`` argument.
        """
        super(SimpleAsyncHTTPClient, self).initialize(defaults=defaults)
        self.max_clients = max_clients
        self.queue = collections.deque()
        self.active = {}
        self.waiting = {}
        self.max_buffer_size = max_buffer_size
        self.max_header_size = max_header_size
        self.max_body_size = max_body_size
        # TCPClient could create a Resolver for us, but we have to do it
        # ourselves to support hostname_mapping.
        if resolver:
            self.resolver = resolver
            self.own_resolver = False
        else:
            self.resolver = Resolver()
            self.own_resolver = True
        if hostname_mapping is not None:
            self.resolver = OverrideResolver(resolver=self.resolver,
                                             mapping=hostname_mapping)
        self.tcp_client = TCPClient(resolver=self.resolver) 
開發者ID:tp4a,項目名稱:teleport,代碼行數:58,代碼來源:simple_httpclient.py

示例13: __init__

# 需要導入模塊: from tornado import tcpclient [as 別名]
# 或者: from tornado.tcpclient import TCPClient [as 別名]
def __init__(self, host, port, secure=True, verify_certificate=True,
                 ssl_key=None, ssl_cert=None,
                 max_active_requests=10, io_loop=None,
                 auto_reconnect=False,
                 auto_reconnect_interval=DEFAULT_RECONNECT_INTERVAL,
                 _connection_cls=HTTP2ClientConnection,
                 _stream_cls=HTTP2ClientStream, **kwargs):

        if getattr(self, 'initialized', False):
            return
        else:
            self.initialized = True

        self.io_loop = io_loop or IOLoop.instance()

        self.host = host
        self.port = port

        self.secure = secure
        self.verify_certificate = verify_certificate
        self.ssl_key = ssl_key
        self.ssl_cert = ssl_cert

        self.closed = False

        self.connection_timeout = kwargs.get(
            'connection_timeout', DEFAULT_CONNECTION_TIMEOUT
        )

        self.auto_reconnect = auto_reconnect
        self.auto_reconnect_interval = auto_reconnect_interval
        self.max_active_requests = max_active_requests

        self.pending_requests = collections.deque()
        self.queue_timeouts = dict()
        self.active_requests = dict()

        self.connection_cls = _connection_cls
        self.stream_cls = _stream_cls

        self.tcp_client = TCPClient()

        self.connection = None

        self.connect() 
開發者ID:vladmunteanu,項目名稱:th2c,代碼行數:47,代碼來源:client.py


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