# 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())
你可以在不同的Python控制台中执行客户端的代码。如果服务端正在运行,控制台中会输出下面的内容:
Lines received b'First line.\n' b'Second line.\n' b'Third line.\n' b'Last line.\n'执行服务端代码的Python控制台会显示下面的内容:
Connection received! b'First line.\nSecond line.\nThird line.\nLast line.\n'首先,让我们关注一下服务端的代码。在创建完一个叫loop的事件循环之后,代码会调用loop.run_until_complete来运行这个simple_echo_server协程。该协程调用asyncio.start_server协程来开启一个socket服务器,绑定到指定的主机和端口号,之后,对每一个客户端连接执行作为参数传入的回调函数——client_connected_handler。在这个例子中,client_connected_handler是另一个协程,并且不会被自动的转换为一个Task。除了协程(coroutine)之外,你可以指定一个普通的回调函数。
《Python核心编程 第二版》.(Wesley J. Chun ).[高清PDF中文版]
《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码]
在Ubuntu下用Python搭建桌面算法交易研究环境