Running multiple sockets using asyncio in python

本秂侑毒 提交于 2021-02-17 01:52:24

问题


Setup: Python 3.7.4

I am trying to create 6 sockets using asyncio listening on different ports. I tried to implement it like this.

Code:

import asyncio

async def client_thread(reader, writer):
  while True:
    package_type = await reader.read(100)
    if not package_type:
        break
    if(package_type[0] == 1) :
        nn_output = get_some_bytes1
    elif (package_type[0] == 2) :
        nn_output = get_some_bytes2
    elif (package_type[0] == 3) :
        nn_output = get_some_bytes3
    elif (package_type[0] == 4) :
        nn_output = get_some_bytes4
    elif (package_type[0] == 5) :
        nn_output = get_some_bytes5         
    else:
        nn_output = get_bytes
    writer.write(nn_output)
    await writer.drain()
    
async def start_servers(host, port):
 server = await asyncio.start_server(client_thread, host, port)
 await server.serve_forever()

def enable_sockets():
 try:
    host = '127.0.0.1'
    port = 60000
    sockets_number = 6
    for i in range(sockets_number):
        asyncio.run(start_servers(host,port+i))
 except:
    print("Exception")

enable_sockets()

So when i receive a call from a client on port 60000 depending on the type of request to be able to serve the client while i serve another client on port 60001.

Each client will send values from 1 to 5. Client 1 -> 1 Client 2 -> 2 etc.

The code is failing at this moment at package_type = await reader.read(100) when i try to start the server


回答1:


Rewrite your enable_sockets function like this:

def enable_sockets():
    try:
        host = '127.0.0.1'
        port = 60000
        sockets_number = 6
        loop = asyncio.get_event_loop()
        for i in range(sockets_number):
            loop.create_task(start_servers(host,port+i))
        loop.run_forever()
    except Exception as exc:
        print(exc)


来源:https://stackoverflow.com/questions/62571622/running-multiple-sockets-using-asyncio-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!