在 python 中使用 asyncio 运行多个套接字 [英] Running multiple sockets using asyncio in python
问题描述
设置:Python 3.7.4
Setup: Python 3.7.4
我正在尝试使用异步侦听不同端口来创建 6 个套接字.我试着像这样实现它.
I am trying to create 6 sockets using asyncio listening on different ports. I tried to implement it like this.
代码:
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()
因此,当我在端口 60000 上收到来自客户端的呼叫时,取决于能够为客户端提供服务的请求类型,而我在端口 60001 上为另一个客户端提供服务.
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.
每个客户端将发送从 1 到 5 的值.客户端 1 ->1 客户端 2 ->2 等
Each client will send values from 1 to 5. Client 1 -> 1 Client 2 -> 2 etc.
当我尝试启动服务器时,代码在 package_type = await reader.read(100) 处失败
The code is failing at this moment at package_type = await reader.read(100) when i try to start the server
推荐答案
像这样重写你的 enable_sockets
函数:
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)
这篇关于在 python 中使用 asyncio 运行多个套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!