Skip to content

Instantly share code, notes, and snippets.

@imalsogreg
Created January 12, 2016 21:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imalsogreg/050b35bd45f4d66eb02b to your computer and use it in GitHub Desktop.
Save imalsogreg/050b35bd45f4d66eb02b to your computer and use it in GitHub Desktop.
import websocket
try:
import thread
except ImportError: #TODO use Threading instead of _thread in python3
import _thread as thread
import time
import sys
def on_message(ws, message):
print(message)
def on_error(ws, error):
print(error)
def on_ping(ws,m):
print("PING: " + m)
def on_pong(ws, m):
print("PONG: " + m)
def on_close(ws):
print("### closed ###")
def on_open(ws):
def run(*args):
time.sleep(1)
for i in range(61):
# send the message, then wait
# so thread doesn't exit and socket
# isn't closed
ws.send("Hello %d" % i)
time.sleep(1)
time.sleep(1)
ws.close()
print("Thread terminating...")
thread.start_new_thread(run, ())
if __name__ == "__main__":
websocket.enableTrace(True)
if len(sys.argv) < 2:
host = "ws://localhost:8000"
else:
host = sys.argv[1]
ws = websocket.WebSocketApp(host,
on_message = on_message,
on_error = on_error,
on_ping = on_ping,
on_pong = on_pong,
on_close = on_close)
ws.on_open = on_open
ws.run_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment