Python Forum

Full Version: Fetching the port number using asyncio
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Below is the code for multisocket server interacting with client. Port Numbers are pre-assigned as 1000 to 4000 for clients
In the client thread function, writer.get_extra_Info does not fetch the port number(ie.. 1000 to 4000) but displays the random number.
Please advice as how to modify the code below to fetch the correct port Number

import asyncio

async def client_thread(reader, writer):
  while True:
   data = (await reader.read(1024))
   if data:
            msg=data.decode()
            addr,port=writer.get_extra_info("peername")
            print("Message from", addr,port)
            writer.write(data)
            await writer.drain()           
   else:
            writer.close()
            print("Connection Closed with the client",addr,port)
            return
      
async def start_servers(host, port):
 server = await asyncio.start_server(client_thread, host, port)
 await server.serve_forever()

def enable_sockets():
 try:
        host = '10.102.3.16'
        port = 1000
        sockets_number = 4
        loop = asyncio.get_event_loop()
        for i in range(sockets_number):
            loop.create_task(start_servers(host,port*(i+1)))
            print("Connected to Ports:",host,port*(i+1))
        loop.run_forever()
 except Exception as exc:
        print(exc)

enable_sockets()