本文整理汇总了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)
示例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
示例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)
示例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)
示例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()
示例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()
)
示例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
)
示例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)
示例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
示例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)
示例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,
)
示例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)
示例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()