简体   繁体   中英

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

The documentation for the library shows that the following code should to the deal and it really works:

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

But the new Python-3.7 asyncio library added the asyncio.run which "runs the passes coroutine" and "should be used as a main entry point for asyncio programs." Moreover, when looking at the documentation for the get_event_loop() used above it reads:

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

I tried tho use the run in the following ways:

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

from which I get a:

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

Then I tried wrapping up the server in a Task by doing:

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

from which I get a:

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

Because of this last warning, I also tried:

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

To which I get the same error. What am I missing here? Moreover, if the asyncio.run does not start a running loop, what does it do?

This should work. wait_closed is the awaitable that you've been looking for.

 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函数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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