【发布时间】:2020-07-10 17:15:46
【问题描述】:
我目前正在尝试将 websocket 接口集成到我的程序中。为此,我使用了 https://websockets.readthedocs.io/en/stable/intro.html 模块以及 asyncio。我目前正在努力在一个专用类中实现 websocket 功能,该类将 websocket 任务设置为在与 MyDriver 类中运行的任务相同的事件循环中并发运行。
main.py
from myDriver import MyDriver
from webSocketServer import WebSocketServer
async def main():
# loop = asyncio.get_event_loop()
driver = MyDriver()
ws = WebSocketServer()
await driver.drive()
# The following does not integrate properly with the above. The msgHandler is not ran
await websockets.serve(lambda websocket, path: ws.msgHandler(websocket, path), "localhost", 5678)
asyncio.run(main())
这里的 lambda 是为了摆脱来自类的 self 参数。
webSocketServer.py
import asyncio
import websockets
class WebSocketServer:
def __init__(self):
print('Init')
async def msgHandler(self, websocket, path):
self.sendTask = asyncio.create_task(self.sendHandler(websocket, path))
self.receiveTask = asyncio.create_task(self.receiveHandler(websocket, path))
await asyncio.wait([self.sendTask, self.receiveTask], return_when=asyncio.FIRST_COMPLETED)
async def sendHandler(self, websocket, path):
while True:
await asyncio.sleep(2)
message = producer()
await websocket.send(message)
async def receiveHandler(self, websocket, path):
async for message in websocket:
await self.printMsg()
async def printMsg(self, msg):
await asyncio.sleep(0.1)
print(msg)
def producer():
return 'Hi !'
我的实现基于 websockets 入门页面上提供的示例。他们使用loop.run_until_complete(server) 和loop.run_forever() API。我还尝试通过将loop in 参数传递给WebSocketServer(loop) 的构造函数并在那里执行websockets.serve(lambda websocket, path: ws.msgHandler(websocket, path), "localhost", 5678) 来使用这些,但随后我收到错误RuntimeError: This event loop is already running。我还看了loop.create_task(),它以协程为参数。
有没有人看到我可以正确集成在与我的其他任务相同的事件循环中运行的 websocket 服务器的方法?谢谢!
【问题讨论】:
标签: python-3.x websocket python-asyncio