import asyncio
class SimpleEchoProtocol(asyncio.Protocol):
def connection_made(self, transport):
"""
Called when a connection is made.
The argument is the transport representing the pipe connection.
To receive data, wait for data_received() calls.
When the connection is closed, connection_lost() is called.
"""
print("Connection received!")
self.transport = transport
def data_received(self, data):
"""
Called when some data is received.
The argument is a bytes object.
"""
print(data)
self.transport.write(b'echo:')
self.transport.write(data)
def connection_lost(self, exc):
"""
Called when the connection is lost or closed.
The argument is an exception object or None (the latter
meaning a regular EOF is received or the connection was
aborted or closed).
"""
print("Connection lost! Closing server...")
server.close()
loop = asyncio.get_event_loop()
server = loop.run_until_complete(loop.create_server(SimpleEchoProtocol, 'localhost', 2222))
loop.run_until_complete(server.wait_closed())
echo:abecho:bcecho:c
Connection received! b'a' b'b' b'c' Connection lost! Closing server...
import asyncio
@asyncio.coroutine
def simple_echo_server():
# Start a socket server, call back for each client connected.
# The client_connected_handler coroutine will be automatically converted to a Task
yield from asyncio.start_server(client_connected_handler, 'localhost', 2222)
@asyncio.coroutine
def client_connected_handler(client_reader, client_writer):
# Runs for each client connected
# client_reader is a StreamReader object
# client_writer is a StreamWriter object
print("Connection received!")
while True:
data = yield from client_reader.read(8192)
if not data:
break
print(data)
client_writer.write(data)
loop = asyncio.get_event_loop()
loop.run_until_complete(simple_echo_server())
try:
loop.run_forever()
finally:
loop.close()
import asyncio
LASTLINE = b'Last line.\n'
@asyncio.coroutine
def simple_echo_client():
# Open a connection and write a few lines by using the StreamWriter object
reader, writer = yield from asyncio.open_connection('localhost', 2222)
# reader is a StreamReader object
# writer is a StreamWriter object
writer.write(b'First line.\n')
writer.write(b'Second line.\n')
writer.write(b'Third line.\n')
writer.write(LASTLINE)
# Now, read a few lines by using the StreamReader object
print("Lines received")
while True:
line = yield from reader.readline()
print(line)
if line == LASTLINE or not line:
break
writer.close()
loop = asyncio.get_event_loop()
loop.run_until_complete(simple_echo_client())
Lines received b'First line.\n' b'Second line.\n' b'Third line.\n' b'Last line.\n'
Connection received! b'First line.\nSecond line.\nThird line.\nLast line.\n'
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有