I would like to run two simple TCP servers in one script using asyncio in python (Python 3.9.9). Each server runs on a different port, obviously. I am having trouble with the correct syntax to use to create and launch the two servers at the same time. Below is what I have so far, but I keep getting RuntimeError: This event loop is already running.
I have seen the way to do this using just a function and loop.start_server, but I need to use the asyncio.Protocol class so that I can have access to the callbacks for conection_made and connection_lost. I don't know if I need loop.create_server or some other syntax, but whatever I am doing is obviously wrong. So how do I do this with asyncio.Protocol?
Note: Both of these servers are meant to run forever. Clients may connect and disconnect butthe servers should run forever.
###############################################################################
# echoserver.py
# Simple code to run EchoServer on two ports simultaneously
###############################################################################
import asyncio
FIRST_PROCESS_PORT =14401
SECOND_PROCESS_PORT =14402
class MyLogger(object):
def info(self,s):
print(s)
logger = MyLogger()
#
# EchoServer class
#
class EchoServer(asyncio.Protocol):
def __init__(self):
self.client_info=None
# Begin asyncio.Protocol overrides
def connection_made(self,transport):
self.transport = transport
self.client_info = self.transport.get_extra_info('peername')
logger.info('connection_made from: %s' % self.client_info)
def connection_lost(self, reason):
logger.info( 'connection_lost: %s | %s' % (self.client_info, reason))
def data_received(self,data):
print("Received: %s" % str(data))
self.transport.write(data)
async def main():
global server1
global server2
loop = asyncio.get_running_loop()
factory1 = await loop.create_server(lambda: EchoServer(),"localhost",FIRST_PROCESS_PORT)
factory2 = await loop.create_server(lambda: EchoServer(),"localhost",SECOND_PROCESS_PORT)
server1 = await loop.run_until_complete(factory1)
server2 = await loop.run_until_complete(factory2)
async with server1, server2:
await asyncio.gather(server1.run_forever(),server2.run_forever())
print("Main done");
###################
# main code here
###################
if __name__ == "__main__":
asyncio.run(main())
print("Done");