2

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

3
  • 2
    asyncio.run(client_thread(host,port+i)) Did you mean asyncio.run(start_servers(host,port+i))? Also you should use create_task instead of run and do loop.run_forever() at the end of your try block. Commented Jun 25, 2020 at 9:03
  • 1
    Can you explain a bit why ? Or maybe you can add an answer below with the piece of code modified cos i am a bit confused with loop.run_forever() :) Commented Jun 25, 2020 at 9:09
  • Something like this ? loop = asyncio.get_event_loop() for i in range(sockets_number): loop.create_task(start_servers(host,port+i)) loop.run_forever() Commented Jun 25, 2020 at 9:25

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.