Ravi
Ravi

Reputation: 737

Implement a simple echo server using asyncio

I am trying to implement a simple echo server using asyncio. Here's my attempt:

import asyncio

async def process(reader, writer):
    while True:
        data = await reader.readline()
        writer.write(data)

loop = asyncio.get_event_loop()
listener = asyncio.start_server(process, host=None, port=2500)
loop.run_until_complete(listener)
loop.run_forever()

This starts the server and I can connect from multiple clients, also the clients have their messages echoed back to them. The problem is when I close one of the clients, the echo messages stop appearing on the other connected clients too. Why does that happen and how can I prevent that?

Upvotes: 3

Views: 1426

Answers (1)

VPfB
VPfB

Reputation: 17387

The server hangs because the loop is not exited when a connection is closed. The convention is when a network read function returns no data, it means EOF. The server must handle it, e.g.:

while True:
    data = await reader.readline()
    if not data:
        break
    writer.write(data)

Without the break the loop is executed again and again, because the EOF state will not change.

Please note that each connection is handled by its own process which is called with a reader and a writer belonging to that connection.

Upvotes: 2

Related Questions