如何正确实现一次接收和发送

问题描述

我正在尝试弄乱 Websockets 模块并在检查主页之后: https://websockets.readthedocs.io/en/stable/intro.html

我做了以下:

服务器

# SERVER

import  asyncio
import websockets
import nest_asyncio

USERS = {}

async def set_online(websocket,user_name):
    USERS[user_name] = websocket
    await notify()
    
async def set_offline(websocket,user_name):
    USERS.pop(user_name,None)
    await notify()


async def notify():
    if USERS:
        message = "Online users: {}\n".format(len(USERS))
        print (message)
        #await asyncio.wait([user.send(message) for user in USERS])
    else:
        message = "Online users: 0\n"
        print (message)
        
        
async def server(websocket,path):
    user_name = await websocket.recv()
    await set_online(websocket,user_name)
        
    try:
        async for message in websocket:
            for user_name,user_ws in USERS.items():
                if websocket == user_ws:
                    print (f"{user_name}: {message}")
            
    finally:
        await set_offline(websocket,user_name)
        


start_server = websockets.serve(server,"localhost",3000,ping_interval=None)

nest_asyncio.apply()

loop = asyncio.get_event_loop()
loop.run_until_complete(start_server)
loop.run_forever()

还有:

客户

# CLIENT

import asyncio
import websockets
import nest_asyncio


async def client(localhost,port):
    uri = "ws://{0}:{1}".format(localhost,str(port))
    async with websockets.connect(uri) as websocket:
        user_name = input("set your name: ")
        await websocket.send(f"{user_name}")
        
        while True:
            message = input("> ")

            if message == "/quit":
                break
            else:
                await websocket.send(message)

host = "localhost"
port = 3000

nest_asyncio.apply()

loop = asyncio.get_event_loop()
loop.run_until_complete(client(host,port))

所以一切都按预期工作,但我想实现每个用户也可以从其他用户那里收到答案。 我发现当我想在服务器端的 for 循环 websocket.send(message) 中使用 async for message in websocket: 时存在冲突

我粘贴在上面的链接,我认为有一个解决方案,但我正在努力弄清楚如何在我的脚本中正确使用它。 我相信我需要创建两个并行工作的任务(发送和接收)。

喜欢:

async def handler(websocket,path):
    consumer_task = asyncio.ensure_future(consumer_handler(websocket,path))
    producer_task = asyncio.ensure_future(producer_handler(websocket,path))
    done,pending = await asyncio.wait([consumer_task,producer_task],return_when=asyncio.FIRST_COMPLETED)
    for task in pending:
        task.cancel()

我在上面提供的网站上显示了以下内容,只需将asyncio.ensure_future更改为asyncio.create_task一件事。我实现了函数 handlerproducerconsumerproducer_handlerconsumer_handler 以使其工作但没有运气。

有人可以提供一个例子或应该如何正确设置吗? 我相信 asyncio.create_task 应该在两者(SERVER 和 CLIENT)上使用,以便它们同时接收和发送。

这很长,但我希望有人可以帮助我,也许我的脚本部分也会对某人有用!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...