使用 Clients and Servers
在上面的例子中,telnet是一个客户端。asyncio模块提供了一个协程方便你很容易的使用stream reader 和 writer来编写服务端和客户端。下面的代码演示了一个简单的echo server,该server监听localhost上的2222端口。你可以在Python的控制台中运行下面的代码,之后在另一个Python的控制台中运行客户端的代码作为客户端。
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()
下面的代码演示了一个客户端程序连接了localhost上的2222端口,并且使用asyncio.StreamWriter对象写了几行数据,之后使用asyncio.StreamWriter对象读取服务端返回的数据。
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())