gpt4 book ai didi

python-3.x - asyncio - 如何在不停止事件循环的情况下停止(并重新启动)服务器?

转载 作者:行者123 更新时间:2023-12-04 01:23:49 26 4
gpt4 key购买 nike

在这种情况下,我正在使用 websockets 模块。
一个典型的服务器实现是这样的:

import websockets
start_server = websockets.serve(counter, "localhost", 6789)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

但是,我希望能够在不停止事件循环的情况下停止并重新启动服务器。从我看到的关于异步服务器的最小文档中,我不清楚如何做到这一点。我也不知道 websockets 是否以完全相同的方式实现。

例如,如果我做这样的事情:
def counter():
start_server = websockets.serve(connection_handler, 'localhost', 6789)
this = loop.run_until_complete(start_server)
try:
loop.run_forever()
finally:
this.close()
loop.run_until_complete(this.wait_closed())


loop = asyncio.get_event_loop()
loop.create_task(anothertask)
startcounter = counter()

我可以通过调用 loop.stop() 来触发服务器停止。如何在不停止循环的情况下停止服务器(并扰乱循环上运行的另一个任务)?

最佳答案

您可以使用 asyncio.create_task在循环已经运行时提交任务。 run_until_complete()后跟 run_forever()模式现已弃用,因为它与 asyncio.run 不兼容,这是现在运行 asyncio 代码的首选方式。

推荐的方法是使用 asyncio.run在顶层启动一个异步入口点(通常定义为 async def main() ),然后从那里完成其余的工作。 run_until_complete(x)然后变成简单的await x , 和 run_forever()不需要,因为您可以等待 server.serve_forever() 之类的内容或 asyncio.Event您的选择。

由于serve_forever websockets 服务器似乎不存在,这是带有事件的变体(未经测试):

async def connection_handler(...):
...

async def test(stop_request):
# occasionally stop the server to test it
while True:
await asyncio.sleep(1)
print('requesting stop')
stop_request.set()

async def main():
stop_request = asyncio.Event()
asyncio.create_task(test(stop_request))
while True:
print('starting the server')
server = await websockets.serve(connection_handler, 'localhost', 6789)
await stop_request.wait()
stop_request.clear()
print('stopping the server')
server.close()
await server.wait_closed()

asyncio.run(main())

关于python-3.x - asyncio - 如何在不停止事件循环的情况下停止(并重新启动)服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62205620/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com