Asyncio服务器在第一个请求后停止响应

时间:2018-11-07 11:32:42

标签: python-3.x python-asyncio

我正在尝试编写基于异步的服务器。问题是,它在第​​一个请求后停止响应。

我的代码基于this template for echo-serverthis method to pass parameters to coroutines

class MsgHandler:

    def __init__(self, mem):
        # here (mem:dict) I store received metrics
        self.mem = mem

    async def handle(self, reader, writer):
        #this coroutine handles requests
        data = await reader.read(1024)
        print('request:', data.decode('utf-8'))
        # read_msg returns an answer based on the request received
        # My server closes connection on every second request
        # For the first one, everything works as intended,
        # so I don't thik the problem is in read_msg()
        response = read_msg(data.decode('utf-8'), self.mem)
        print('response:', response)
        writer.write(response.encode('utf-8'))
        await writer.drain()
        writer.close()


def run_server(host, port):
    mem = {}
    msg_handler = MsgHandler(mem)

    loop = asyncio.get_event_loop()
    coro = asyncio.start_server(msg_handler.handle, host, port, loop=loop)
    server = loop.run_until_complete(coro)

    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass

    server.close()
    loop.run_until_complete(server.wait_closed())
    loop.close()

在客户端,我得到一个空响应或ConnectionResetError(104,“对等重置连接”)。

1 个答案:

答案 0 :(得分:0)

您在处理程序中使用 writer.close() 关闭编写器,这会关闭套接字。

来自 StreamWriter 的 3.9 文档:

enter image description here

此外,如果您不关闭流编写器,那么您仍会将其存储在某处,以便继续通过同一连接接收消息。