Running multiple servers in one event loop

3,430 views
Skip to first unread message

Kashif Razzaqui

unread,
Jan 18, 2015, 2:05:01 AM1/18/15
to python...@googlegroups.com
Can the asyncio event loop run more than one server(on different ports with different protocols) - I feel it should be able to do that but I am not certain how. 
Can anyone show a trivial example of how this can be done?

coles...@gmail.com

unread,
Jan 18, 2015, 9:29:26 PM1/18/15
to Kashif Razzaqui, python...@googlegroups.com
Yup. It definitely can.
Just use loop.run_until_complete(asyncio.create_server(...)) or loop.run_until_complete(asyncio.start_server(...)) as many times as you need before calling loop.run_forever().

Here's a short example that runs a TCP server listening on three different ports (very similar to https://docs.python.org/3/library/asyncio-stream.html#tcp-echo-server-using-streams ).

#!/usr/bin/python3.4
import asyncio

@asyncio.coroutine
def handle_hello(reader, writer):
    peer = writer.get_extra_info('peername')
    writer.write("Hello, {0[0]}:{0[1]}!\n".format(peer).encode("utf-8"))
    writer.close()

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    servers = []
    for i in range(3):
        print("Starting server {0}".format(i+1))
        server = loop.run_until_complete(
                asyncio.start_server(handle_hello, '127.0.0.1', 8000+i, loop=loop))
        servers.append(server)

    try:
        print("Running... Press ^C to shutdown")
        loop.run_forever()
    except KeyboardInterrupt:
        pass

    for i, server in enumerate(servers):
        print("Closing server {0}".format(i+1))
        server.close()
        loop.run_until_complete(server.wait_closed())
    loop.close()


Cheers,
David

Kashif Razzaqui

unread,
Jan 18, 2015, 10:01:47 PM1/18/15
to coles...@gmail.com, python...@googlegroups.com

Thanks David, this clarifies it.

Reply all
Reply to author
Forward
0 new messages