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

2024-06-07 15:15:00 发布

您现在位置:Python中文网/ 问答频道 /正文

documentation for the library表明以下代码应该用于交易,并且它确实有效:

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 library添加了asyncio.run,它将作为异步程序的主入口点来运行passes coroutine

Application developers should typically use the high-level asyncio functions, such as asyncio.run()...

我试着用以下方法来使用跑步:

^{pr2}$

从中我得到一个:

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())

我也有同样的错误。我错过了什么? 此外,如果异步运行不启动运行循环,它做什么?在


Tags: therunloopeventasynciolocalhosthellowebsockets

热门问题