Issue
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");
Solution
I've made some simple rearrangements to make the server work on two ports:
###############################################################################
# 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()
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(f"connection_made from: {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():
loop = asyncio.get_running_loop()
server1 = await loop.create_server(
EchoServer, "0.0.0.0", FIRST_PROCESS_PORT
)
server2 = await loop.create_server(
EchoServer, "0.0.0.0", SECOND_PROCESS_PORT
)
# serve forever
async with server1, server2:
while True:
await asyncio.sleep(3600)
if __name__ == "__main__":
asyncio.run(main())
This will create two ports on all interfaces (0.0.0.0
), but you can change it to localhost
.
On other terminal if you run:
echo "Hello World" | nc -N <your IP address> 14401
echo "Hello World" | nc -N <your IP address> 14402
the server responds:
connection_made from: ('XXX', 41760)
Received: b'Hello World\n'
connection_lost: ('XXX', 41760) | None
connection_made from: ('XXX', 32872)
Received: b'Hello World\n'
connection_lost: ('XXX', 32872) | None
Answered By - Andrej Kesely
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.