aaa
aaa

Reputation: 715

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.

Upvotes: 16

Views: 32925

Answers (3)

Piyush
Piyush

Reputation: 1

The documentation says to use an asynchronous dispatcher like rel. It will handle keyboard interrupt and then you can pass in a custom callback function while registering for keyboard interrupt event

Upvotes: 0

vc 74
vc 74

Reputation: 38179

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

Upvotes: 10

aaa
aaa

Reputation: 715

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"

Upvotes: 21

Related Questions