在 python 中使用 asyncio 运行多个套接字

编程入门 行业动态 更新时间:2024-10-27 20:37:54
本文介绍了在 python 中使用 asyncio 运行多个套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

设置: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 运行多个套接字

本文发布于:2023-11-23 09:27:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1620938.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   python   asyncio

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!