简体   繁体   English

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

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

I have server, where I need to keep connection with client as long as possible. 我有服务器,需要与客户端保持尽可能长的连接时间。 I need to allow for multiple clients connect to this server. 我需要允许多个客户端连接到该服务器。 Code: 码:

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)

The problem: currently only one client can connect to this server. 问题:目前只有一个客户端可以连接到该服务器。 It seems socket do not closing properly. 似乎套接字未正确关闭。 And because of this even previous client cannot reconnect. 因此,即使以前的客户端也无法重新连接。 I think this is because infinite loop exists. 我认为这是因为存在无限循环。 How to fix this problem? 如何解决这个问题?

The while loop is correct. while循环是正确的。

If you wanted a server that waits on data from a client you would have the following loop in your handle_connection. 如果希望服务器等待来自客户端的数据,则handle_connection中将具有以下循环。

while 1:
    data = await reader.read(100)
    # Do something with the data

See the example echo server here for more details on reading / writing. 有关读取/写入的更多详细信息,请参见此处的示例echo服务器。

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

Your problem is likely that this function doesn't return and is looping itself without await'g anything. 您的问题很可能是此函数不返回,并且在不等待任何内容的情况下循环自身。 That would mean the asyncio loop would never regain control so new connections could not be made. 这意味着异步循环永远不会重新获得控制权,因此无法建立新的连接。

await auth.process()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM