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
asyncio.run(client_thread(host,port+i))Did you meanasyncio.run(start_servers(host,port+i))? Also you should usecreate_taskinstead ofrunand doloop.run_forever()at the end of your try block.