python - 如何停止 Python Websocket 客户端 "ws.run_forever"

标签 python websocket

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

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

最佳答案

在 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 - 如何停止 Python Websocket 客户端 "ws.run_forever",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38995640/

相关文章:

python - 在 Python 中打开带有自定义 cookie 的网页

javascript - 从 native WebSocket 到 Socket.IO 服务器的调用事件

PHP Ratchet 网络套接字$conn->send($msg)!如何在客户端获取此消息?

iis - IIS 上托管的 ASP.NET 5 (DNX) 中的 WebSocket 无法正常工作

GO - 代码在函数返回后停止执行

python - xPath:将表达式与实际源代码匹配困难

python dicttoxml 多次使用相同的键

python - 在 Jupyter 笔记本中更改 HTML 表中文本的对齐方式

java - 调用 sendText() 方法时,Tomcat 8.0.33 的 Websocket 实现不会立即抛出 IOException(服务器端)

python - Cython 的扩展模块的类的方法不可见/给出名称提及时出错