Python Websockets-类中的等待问题

Python Websockets-类中的等待问题,python,websocket,python-asyncio,Python,Websocket,Python Asyncio,您好,我正在编写一个简单的视频聊天应用程序服务器,遇到了一个问题,我无法在Room类中等待函数send\u to\u all()。我是asyncio新手,不知道该怎么做 我曾尝试过使用线程和一些我在网上发现的异步方法,但都不起作用 class Room: def __init__(self,_id,owner): self.owner = owner self.id = _id self.participants = []

您好,我正在编写一个简单的视频聊天应用程序服务器,遇到了一个问题,我无法在Room类中等待函数
send\u to\u all()
。我是asyncio新手,不知道该怎么做

我曾尝试过使用线程和一些我在网上发现的异步方法,但都不起作用

class Room:
     def __init__(self,_id,owner):
          self.owner = owner
          self.id = _id
          self.participants = []
          
          print("[DEBUG] New room has been created")
          
     async def send_msg_to_all(self, message):
          print("[DEBUG] Sending message")
          for participant in self.participants:
               await participant.conn.send(message)
运行上面的代码后,我得到RuntimeError

RuntimeWarning: coroutine 'Room.send_msg_to_all' was never awaited
  self.send_msg_to_all(str(serialized_partipants_info))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
根据以下说明,您不能等待任何正常功能:

如果一个对象可以用在等待表达式中,我们就说它是一个等待对象。等待对象有三种主要类型:协同程序、任务和未来

您必须使用一个使用异步功能创建的库,例如。 请记住,您不能等待已经等待的异步调用。 我自己没有使用asyncore包,所以您必须了解它的用法。但在一般情况下,您必须定义单独的异步函数,然后按如下方式收集它们:

async def async_method1(*args):
  #do your thing

async def async_method1(*args):
  #do your thing

async def async_method1(*args):
  #do your thing

async def all_my_calls(*args):
  reslist = await asyncio.gather(
        async_method1(*args),
        async_method2(*args),
        async_method3(*args))
  # do stuff with your reslist


asyncio.run(all_my_calls(*args))
请记住,根据您的逻辑,您可能不需要任何输入
*args
或输出
reslist
。我只是将它们包含在我的代码中,以便您知道如何传递参数并在需要时处理结果

编辑


正如Tomek Pulkiewicz在评论中已经提到的,asyncore仅用于普通套接字。如果要使用异步web套接字use

,则只能等待异步函数,而不能在循环中多次等待函数。我可以看出这两件事是错误的。但是你也应该发布你的错误日志。哦,我忘了,谢谢你提醒我这些只是警告,不是错误。我知道,但问题是参与者。conn.send(message)由于websockets模块要求是participant.conn.send一个异步函数或它只是一个普通函数,所以必须等待该行?好的,现在我明白了,但我真的不知道如何在代码中实现它。我的reslist应该是这样的reslist=await asyncio.gather(x.conn.send(message)for x in self.participants)还是how PS:感谢您的帮助answer@TomekPulkiewicz我自己没有使用asyncore,也许你应该深入研究一下。但通常您应该为每个异步函数定义不同的异步函数。每个异步方法都应该单独定义。我会将它们的定义添加到我的代码中。哦,谢谢这是我要找的帖子。哦,但我认为这只适用于普通套接字,而不是WebSocket。但我发现了一个使用WebSocket的库,感谢您设置了我的track@TomekPulkiewicz我会将您找到的库添加到我的答案中,以供其他可能需要它的人使用,谢谢:)