Threaded, non-blocking websocket client

I want to run a Python program that sends a message through web sockets to the Tornado server every second. I used the example on websocket-client;

This example does not work because ws.run_forever() will stop the execution of the while loop.

Can someone give me an example of how to properly implement this as a streaming class, which I can call a sending method, but also receive messages?

 import websocket import thread import time def on_message(ws, message): print message def on_error(ws, error): print error def on_close(ws): print "### closed ###" def on_open(ws): pass if __name__ == "__main__": websocket.enableTrace(True) ws = websocket.WebSocketApp("ws://echo.websocket.org/", on_message = on_message, on_error = on_error, on_close = on_close) ws.on_open = on_open ws.run_forever() while True: #do other actions here... collect data etc. for i in range(100): time.sleep(1) ws.send("Hello %d" % i) time.sleep(1) 
+12
python multithreading websocket
source share
1 answer

Here is an example on the github page that does just that. It seems that you started with this example and took a code that sends messages every second from on_open and inserted them after calling run_forever that BTW works until the socket is disconnected.

You may have problems with basic concepts here. There will always be a thread designed to listen on the socket (in this case, the main thread that goes into the loop inside run_forever, waiting for the message). If you want something else to happen, you will need a different thread.

Below is another version of the sample code, where instead of using the main thread as a "socket listener", another thread is created and run_forever is launched. I find this more complicated since you need to write code to make sure the socket is connected when you can use the on_open callback, but maybe this will help you understand.

 import websocket import threading from time import sleep def on_message(ws, message): print message def on_close(ws): print "### closed ###" if __name__ == "__main__": websocket.enableTrace(True) ws = websocket.WebSocketApp("ws://echo.websocket.org/", on_message = on_message, on_close = on_close) wst = threading.Thread(target=ws.run_forever) wst.daemon = True wst.start() conn_timeout = 5 while not ws.sock.connected and conn_timeout: sleep(1) conn_timeout -= 1 msg_counter = 0 while ws.sock.connected: ws.send('Hello world %d'%msg_counter) sleep(1) msg_counter += 1 
+15
source share

All Articles