简体   繁体   中英

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.

If you wanted a server that waits on data from a client you would have the following loop in your 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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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