我正在使用“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/