0

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?

1
  • Info about client: this is tcp wow client. Commented Feb 11, 2019 at 11:28

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

1 Comment

good explanation! so, if auth.process() will return None, this will be correct result for return?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.