首页 > 解决方案 > Websockets 服务器不会终止

问题描述

我有这个 python 程序。如果我启动它并且没有客户端连接到它,它不会终止。我尝试了control+c,control+z,control+pause,control+break,control+shift+/,向python大神祈祷,但没有。唯一会杀死它的是:

...这两者都非常不方便。

只要我不必为简单的问答服务器编写 60 行代码,我完全可以为其他人放弃这些框架。

谢谢!

import websockets
import asyncio
import time

# socket settings
HOST = '127.0.0.1'  # (localhost)
PORT = 62421        


async def TestingStreaming(websocket, path):
    while True:
        await websocket.send("testing")
        try:
            await websocket.recv()
        except:
            print("Client dropped or left.")
            break
        time.sleep(2)


start_server = websockets.serve(TestingStreaming, host="localhost", port=62421)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

标签: pythonwebsocketpython-asyncio

解决方案


Control+Pause 有效,但仅适用于 PowerShell。


推荐阅读