如何停止 Python Websocket 客户端“ws.run_forever”

新手上路,请多包涵

我正在使用“ws.run_forever”启动我的 Python Websocket,另一个 消息来源 说我应该使用“run_until_complete()”,但这些函数似乎只对 Python asyncio 可用。

如何停止 websocket 客户端?或者如何在不永远运行的情况下启动它。

原文由 Paul 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.6k
2 个回答

还有一个 close 方法 WebSocketAppkeep_running 设置为 False 并关闭套接字

原文由 vc 74 发布,翻译遵循 CC BY-SA 4.0 许可协议

在 python websockets 中,您可以使用“ws.keep_running = False”来停止“永远运行”的 websocket。

这可能有点不直观,您可以选择另一个整体效果更好的库。

下面的代码对我有用(使用 ws.keep_running = False)。

 class testingThread(threading.Thread):
    def __init__(self,threadID):
        threading.Thread.__init__(self)
        self.threadID = threadID
    def run(self):
        print str(self.threadID) + " Starting thread"
        self.ws = websocket.WebSocketApp("ws://localhost/ws", on_error = self.on_error, on_close = self.on_close, on_message=self.on_message,on_open=self.on_open)
        self.ws.keep_running = True
        self.wst = threading.Thread(target=self.ws.run_forever)
        self.wst.daemon = True
        self.wst.start()
        running = True;
        testNr = 0;
        time.sleep(0.1)
        while running:
            testNr = testNr+1;
            time.sleep(1.0)
            self.ws.send(str(self.threadID)+" Test: "+str(testNr)+")
        self.ws.keep_running = False;
        print str(self.threadID) + " Exiting thread"

原文由 Paul 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题