我正在学习使用async def
和await
的py3.5语法中的asyncio库,并尝试编写简单的服务器/客户端架构。
由于某种原因,客户端从未收到消息并提前终止:
IP = ''
PORT = 8880
import asyncio
import multiprocessing
import ssl
async def start_client(loop):
reader, writer = await asyncio.open_connection(IP, PORT, loop=loop)
writer.write("Gimme gimme gimme".encode())
writer.close()
data = await reader.read()
print(data.decode())
loop = asyncio.get_event_loop()
loop.run_until_complete(start_client(loop))
loop.close()
IP = ''
PORT = 8880
import asyncio
import requests
import json
async def handle_echo(reader, writer):
data = await reader.read()
response = await whatsup()
print(response)
writer.write(response.encode())
writer.write_eof()
await writer.drain()
writer.close()
async def whatsup():
return "Hello there!"
loop = asyncio.get_event_loop()
server = asyncio.start_server(handle_echo,
IP,
PORT,
loop=loop)
server = loop.run_until_complete(server)
try:
loop.run_forever()
except:
pass
server.close()
loop.run_until_complete(server.wait_closed())
loop.close()
我观察到的是服务器能够打印出" Hello world!"并成功返回,但是从我可以收集的内容中,客户端总共读取0个字节并且只退出
我尝试过:
while not reader.at_eof():
data = await reader.read(100)
print(data.decode())
但它评估at_eof()
为真,并且也提前退出。
答案 0 :(得分:0)
好的,我找到了解决方案:
read()
会一直读到eof
标记。我们需要双方都writer.write_eof()
才能阅读read()
。
这是解决方案代码:
async def handle_echo(reader, writer):
data = await reader.read()
response = await whatsup()
print(response)
writer.write(response.encode())
writer.write_eof()
await writer.drain()
writer.close()
async def start_client(loop):
reader, writer = await asyncio.open_connection(IP, PORT, loop=loop)
writer.write("Gimme gimme gimme".encode())
writer.write_eof() # crucial here
writer.close()
data = await reader.read()
print(data.decode())