在Python的asyncio websockets库中,示例调用了
如果我注释掉run_forever(),程序会立即结束。
start_server是库返回的可等待对象。为什么run_until_complete不能足够地使其阻塞/等待hello()呢?
run_forever()
。为什么需要这样做?
run_until_complete()
不应该阻塞并运行websockets循环吗?#!/usr/bin/env python
# WS server example
import asyncio
import websockets
async def hello(websocket, path):
name = await websocket.recv()
print(f"< {name}")
greeting = f"Hello {name}!"
await websocket.send(greeting)
print(f"> {greeting}")
start_server = websockets.serve(hello, "localhost", 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
# if you comment out the above line, this doesn't work, i.e., the server
# doesn't actually block waiting for data...
如果我注释掉run_forever(),程序会立即结束。
start_server是库返回的可等待对象。为什么run_until_complete不能足够地使其阻塞/等待hello()呢?
然后...
loop.run_forever() - Anthony Albaadd_reader
、add_writer
、call_later
、call_soon
等等,而正是这些方法需要事件循环实际运行才能保持轮子转动。 - user4815162342