本文整理汇总了Python中tornado.tcpclient.TCPClient类的典型用法代码示例。如果您正苦于以下问题:Python TCPClient类的具体用法?Python TCPClient怎么用?Python TCPClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了TCPClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _run_traffic_jam
def _run_traffic_jam(nsends, nbytes):
# This test eats `nsends * nbytes` bytes in RAM
np = pytest.importorskip('numpy')
from distributed.protocol import to_serialize
data = bytes(np.random.randint(0, 255, size=(nbytes,)).astype('u1').data)
with echo_server() as e:
client = TCPClient()
stream = yield client.connect('127.0.0.1', e.port)
b = BatchedSend(interval=0.01)
b.start(stream)
msg = {'x': to_serialize(data)}
for i in range(nsends):
b.send(assoc(msg, 'i', i))
if np.random.random() > 0.5:
yield gen.sleep(0.001)
results = []
count = 0
while len(results) < nsends:
# If this times out then I think it's a backpressure issue
# Somehow we're able to flood the socket so that the receiving end
# loses some of our messages
L = yield gen.with_timeout(timedelta(seconds=5), read(stream))
count += 1
results.extend(r['i'] for r in L)
assert count == b.batch_count == e.count
assert b.message_count == nsends
assert results == list(range(nsends))
stream.close() # external closing
yield b.close(ignore_closed=True)
示例2: test_stress
def test_stress():
with echo_server() as e:
client = TCPClient()
stream = yield client.connect('127.0.0.1', e.port)
L = []
@gen.coroutine
def send():
b = BatchedSend(interval=3)
b.start(stream)
for i in range(0, 10000, 2):
b.send(i)
b.send(i + 1)
yield gen.sleep(0.00001 * random.randint(1, 10))
@gen.coroutine
def recv():
while True:
result = yield gen.with_timeout(timedelta(seconds=1), read(stream))
print(result)
L.extend(result)
if result[-1] == 9999:
break
yield All([send(), recv()])
assert L == list(range(0, 10000, 1))
stream.close()
示例3: connect
def connect(self, address, deserialize=True, **connection_args):
self._check_encryption(address, connection_args)
ip, port = parse_host_port(address)
kwargs = self._get_connect_args(**connection_args)
client = TCPClient()
try:
stream = yield client.connect(ip, port,
max_buffer_size=MAX_BUFFER_SIZE,
**kwargs)
# Under certain circumstances tornado will have a closed connnection with an error and not raise
# a StreamClosedError.
#
# This occurs with tornado 5.x and openssl 1.1+
if stream.closed() and stream.error:
raise StreamClosedError(stream.error)
except StreamClosedError as e:
# The socket connect() call failed
convert_stream_closed_error(self, e)
local_address = self.prefix + get_stream_address(stream)
raise gen.Return(self.comm_class(stream,
local_address,
self.prefix + address,
deserialize))
示例4: connect
def connect(self):
client = TCPClient(io_loop=self.io_loop)
self.stream = yield client.connect(self.host, self.port)
# sock = None
# try:
# if self.unix_socket and self.host in ('localhost', '127.0.0.1'):
# sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
# t = sock.gettimeout()
# sock.settimeout(self.connect_timeout)
# sock.connect(self.unix_socket)
# sock.settimeout(t)
# self.host_info = "Localhost via UNIX socket"
# if DEBUG: print('connected using unix_socket')
# else:
# while True:
# try:
# sock = socket.create_connection(
# (self.host, self.port), self.connect_timeout)
# break
# except (OSError, IOError) as e:
# if e.errno == errno.EINTR:
# continue
# raise
# self.host_info = "socket %s:%d" % (self.host, self.port)
# if DEBUG: print('connected using socket')
# sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
# if self.no_delay:
# sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
# self.socket = sock
# self._rfile = _makefile(sock, 'rb')
yield self._get_server_information()
yield self._request_authentication()
示例5: __init__
def __init__(self, *args, **kwargs):
TCPClient.__init__(self, kwargs.pop("resolver", None),
kwargs.pop("io_loop", None))
Connection.__init__(self, parser_class=AsyncParser, *args, **kwargs)
self._stream = None
示例6: test_close_twice
def test_close_twice():
with echo_server() as e:
client = TCPClient()
stream = yield client.connect('127.0.0.1', e.port)
b = BatchedSend(interval=10)
b.start(stream)
yield b.close()
yield b.close()
示例7: __init__
def __init__(self, ssl_options=None, gp_module=False, **kwargs):
self.logger = logging.getLogger(self.__class__.__name__)
self.gp_module = gp_module
try:
TCPClient.__init__(self, ssl_options=ssl_options, **kwargs)
except:
etype, evalue, etb = sys.exc_info()
self.logger.error("Could not create tcp client. Exception: %s, Error: %s." % (etype, evalue))
self.gp_module.shutDown()
示例8: test_send_after_stream_finish
def test_send_after_stream_finish():
with echo_server() as e:
client = TCPClient()
stream = yield client.connect('127.0.0.1', e.port)
b = BatchedSend(interval=10)
b.start(stream)
yield b.last_send
b.send('hello')
result = yield read(stream); assert result == ['hello']
示例9: test_send_before_start
def test_send_before_start():
with echo_server() as e:
client = TCPClient()
stream = yield client.connect('127.0.0.1', e.port)
b = BatchedSend(interval=10)
b.send('hello')
b.send('world')
b.start(stream)
result = yield read(stream); assert result == ['hello', 'world']
示例10: connect
def connect(self, host, port):
self.host = host
self.port = port
client = TCPClient()
try:
self.stream = yield client.connect(self.host, self.port)
except IOError as e:
log.error("%s", repr(e))
raise gen.Return((False, 'Failed to connect'))
self.trigger(Event.CONNECT, self)
raise gen.Return((True, "OK"))
示例11: test_close_closed
def test_close_closed():
with echo_server() as e:
client = TCPClient()
stream = yield client.connect('127.0.0.1', e.port)
b = BatchedSend(interval=10)
b.start(stream)
b.send(123)
stream.close() # external closing
yield b.close(ignore_closed=True)
示例12: connect
def connect(ip, port, timeout=1):
client = TCPClient()
start = time()
while True:
try:
stream = yield client.connect(ip, port)
raise Return(stream)
except StreamClosedError:
if time() - start < timeout:
yield gen.sleep(0.01)
logger.debug("sleeping on connect")
else:
raise
示例13: start_app
def start_app():
tcpClient = TCPClient()
try:
stream = yield tcpClient.connect('127.0.0.1', 9999)
print 'Connection started'
app = LaternController(LanternDriver())
client = TLVClient(stream)
executer = ThreadPoolExecutor(max_workers=5)
while True:
command = yield client.getCommand()
executer.submit(app.handle, command)
except Exception as e:
print 'Caught Error: %s' % e
IOLoop.instance().add_callback(IOLoop.instance().stop)
示例14: connect
def connect(ip, port, timeout=3):
client = TCPClient()
start = time()
while True:
try:
future = client.connect(ip, port, max_buffer_size=MAX_BUFFER_SIZE)
stream = yield gen.with_timeout(timedelta(seconds=timeout), future)
raise Return(stream)
except StreamClosedError:
if time() - start < timeout:
yield gen.sleep(0.01)
logger.debug("sleeping on connect")
else:
raise
except gen.TimeoutError:
raise IOError("Timed out while connecting to %s:%d" % (ip, port))
示例15: __init__
def __init__(self):
logger.debug('Starting Envisalink Client')
# Register events for alarmserver requests -> envisalink
events.register('alarm_update', self.request_action)
# Register events for envisalink proxy
events.register('envisalink', self.envisalink_proxy)
# Create TCP Client
self.tcpclient = TCPClient()
# Connection
self._connection = None
# Set our terminator to \r\n
self._terminator = b"\r\n"
# Reconnect delay
self._retrydelay = 10
# Connect to Envisalink
self.do_connect()
# Setup timer to refresh envisalink
tornado.ioloop.PeriodicCallback(self.check_connection, 1000).start()
# Last activity
self._last_activity = time.time()