python - Threaded, non-blocking websocket client -
i wanting run program in python sends message every second via web sockets tornado server. have been using example on websocket-client;
this example not work, because ws.run_forever()
stop execution of while loop.
can give me example of how correctly implement threaded class can both call send method of, 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. in range(100): time.sleep(1) ws.send("hello %d" % i) time.sleep(1)
there's example in github page that. seems started out of example , took code sends messages every second out of on_open , pasted after run_forever call, btw runs until socket disconnected.
maybe having issues basic concepts here. there's going thread dedicated listening socket (in case main thread enters loop inside run_forever waiting messages). if want have other thing going on you'll need thread.
below different version of example code, instead of using main thread "socket listener", thread created , run_forever runs there. see bit more complicated since have write code assure socket has connected while use on_open callback, maybe understand.
import websocket import threading 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 , 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
Comments
Post a Comment