繁体   English   中英

使用 websockets lib 和 Python3.7 启动服务器的适当方法

[英]Appropriate way to start a server using the websockets lib and Python3.7

文档显示以下代码应该适用并且它确实有效:

start_server = websockets.serve(hello, 'localhost', 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

但是新的 Python-3.7 asyncio 库添加了asyncio.run ,它“运行传递协程”并且“应该用作 asyncio 程序的主要入口点”。 此外,在查看上面使用get_event_loop()文档时,它会显示:

应用程序开发人员通常应该使用高级 asyncio 函数,例如 asyncio.run()...

我尝试通过以下方式使用 run:

server = websockets.serve(hello, 'localhost', 8765)
asyncio.run(server)

我从中得到一个:

ValueError: a coroutine was expected, got <websockets.server.Serve object at 0x7f80af624358>
sys:1: RuntimeWarning: coroutine 'BaseEventLoop.create_server' was never awaited

然后我尝试通过执行以下操作将服务器包装在任务中:

server = asyncio.create_task(websockets.serve(handle, 'localhost', 8765))
asyncio.run(server)

我从中得到一个:

RuntimeError: no running event loop
sys:1: RuntimeWarning: coroutine 'BaseEventLoop.create_server' was never awaited

由于最后一个警告,我也尝试过:

async def main():
  server = asyncio.create_task(websockets.serve(hello, 'localhost', 8765))
  await server
asyncio.run(main())

我得到同样的错误。 我在这里缺少什么? 此外,如果asyncio.run没有启动运行循环,它会做什么?

这应该工作。 wait_closed是你一直在寻找的等待。

 async def serve():                                                                                           
      server = await websockets.serve(hello, 'localhost', 8765)
      await server.wait_closed()

 asyncio.run(serve())

其实应该是这样的:await(await server).wait_closed() 因为server没有wait_closed函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM