我正在使用“ws.run_forever”启动我的Python Websocket,另一个源指出我应该使用“run_until_complete()”,但这些函数似乎只适用于Python asyncio。
我如何停止Websocket客户端?或者如何在不永远运行的情况下启动它。
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"
WebSocketApp
还有一个close
方法,该方法将keep_running
设置为False并关闭套接字。
文档中建议使用像rel这样的异步调度程序。它将处理键盘中断,然后您可以在注册键盘中断事件时传递自定义回调函数。
close_connection
函数,该函数设置self.ws.keep_running = False
和self.running = False
。 - JSON_Derulo