Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop Python Websocket client "ws.run_forever"

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.

like image 442
Paul Avatar asked Aug 17 '16 11:08

Paul


People also ask

How do I stop a WebSocket connection?

The WebSocket. close() method closes the WebSocket connection or connection attempt, if any. If the connection is already CLOSED , this method does nothing.

How do I restart a WebSocket in Python?

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.

What is WebSocket client Python?

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.

What is WebSocketApp?

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.


2 Answers

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"
like image 70
Paul Avatar answered Nov 01 '22 23:11

Paul


There's also a close method on WebSocketApp which sets keep_running to False and also closes the socket

like image 29
vc 74 Avatar answered Nov 02 '22 01:11

vc 74