I'm starting my Python Websocket using "ws.run_forever", another source stated that I should use "run_until_complete()" but these functions only seem available to Python asyncio.
How can I stop a websocket client? Or how to start it withouth running forever.
The WebSocket. close() method closes the WebSocket connection or connection attempt, if any. If the connection is already CLOSED , this method does nothing.
Unfortunately you can't “restart” websocket once you've close it with “my_client. stop()” within same process, so if you want to use the websocket again, you need to re-run the code.
websockets is a library for building WebSocket servers and clients in Python with a focus on correctness, simplicity, robustness, and performance. Built on top of asyncio , Python's standard asynchronous I/O framework, it provides an elegant coroutine-based API.
WebSocketApp is a wrapper around WebSocket that provides a more 'event-driven' interface. You provide callbacks to the constructor (or by assignment to the relevant members after initialization), then call run_forever which blocks until the connection is closed.
In python websockets, you can use "ws.keep_running = False" to stop the "forever running" websocket.
This may be a little unintuitive and you may choose another library which may work better overall.
The code below was working for me (using 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"
There's also a close
method on WebSocketApp
which sets keep_running
to False and also closes the socket
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With