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

14

我正在使用“ws.run_forever”启动我的Python Websocket,另一个指出我应该使用“run_until_complete()”,但这些函数似乎只适用于Python asyncio。

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

3个回答

19
在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"

有没有关于替代Python Websocket库的建议? - March Ho
我认为这不是对这篇文章的有效评论,你最好自己创建一个“问题”或使用谷歌寻找其他建议。不过真正的问题是为什么? - Paul
2
我问这个问题是因为你特别指出了问题中的库不直观,这表明存在更好的选择。 - March Ho
嗯,我明白你的观点,虽然那是相当久以前的事情了,而且我还没有深入研究Python。最近我越来越多地使用NodeJS,但这可能完全无关紧要。 - Paul
1
@Paul 我使用了你的解决方案,但添加了一个 close_connection 函数,该函数设置 self.ws.keep_running = Falseself.running = False - JSON_Derulo

7

WebSocketApp还有一个close方法,该方法将keep_running设置为False并关闭套接字。


0

文档中建议使用像rel这样的异步调度程序。它将处理键盘中断,然后您可以在注册键盘中断事件时传递自定义回调函数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接