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
Ricardo gemignani
source share