Python3 asyncio:对多个连接使用无限循环并正确关闭连接

Python3 asyncio: using infinite loop for multiple connections and proper connection closing

我有服务器,我需要尽可能长时间地与客户端保持连接。我需要允许多个客户端连接到该服务器。代码:

class LoginServer(BaseServer):

    def __init__(self, host, port):
        super().__init__(host, port)

    async def handle_connection(self, reader: StreamReader, writer: StreamWriter):
        peername = writer.get_extra_info('peername')
        Logger.info('[Login Server]: Accepted connection from {}'.format(peername))

        auth = AuthManager(reader, writer)

        while True:
            try:
                await auth.process()
            except TimeoutError:
                continue
            finally:
                await asyncio.sleep(1)

        Logger.warning('[Login Server]: closing...')
        writer.close()

    @staticmethod
    def create():
        Logger.info('[Login Server]: init')
        return LoginServer(Connection.LOGIN_SERVER_HOST.value, Connection.LOGIN_SERVER_PORT.value)

问题:目前只有一个客户端可以连接到此服务器。似乎套接字没有正确关闭。因此,甚至以前的客户端也无法重新连接。我认为这是因为存在无限循环。如何解决这个问题?

while 循环是正确的。

如果您想要一个等待来自客户端的数据的服务器,您将在 handle_connection.

中有以下循环
while 1:
    data = await reader.read(100)
    # Do something with the data

有关读取/写入的更多详细信息,请参阅此处的示例回显服务器。

https://asyncio.readthedocs.io/en/latest/tcp_echo.html

你的问题很可能是这个函数没有 return 并且在没有等待任何东西的情况下循环自身。这意味着 asyncio 循环将永远无法重新获得控制权,因此无法建立新的连接。

await auth.process()