1import websocket
2try:
3    import thread
4except ImportError:  # TODO use Threading instead of _thread in python3
5    import _thread as thread
6import time
7import sys
8
9
10def on_message(ws, message):
11    print(message)
12
13
14def on_error(ws, error):
15    print(error)
16
17
18def on_close(ws):
19    print("### closed ###")
20
21
22def on_open(ws):
23    def run(*args):
24        for i in range(3):
25            # send the message, then wait
26            # so thread doesn't exit and socket
27            # isn't closed
28            ws.send("Hello %d" % i)
29            time.sleep(1)
30
31        time.sleep(1)
32        ws.close()
33        print("Thread terminating...")
34
35    thread.start_new_thread(run, ())
36
37if __name__ == "__main__":
38    websocket.enableTrace(True)
39    if len(sys.argv) < 2:
40        host = "ws://echo.websocket.org/"
41    else:
42        host = sys.argv[1]
43    ws = websocket.WebSocketApp(host,
44                                on_message=on_message,
45                                on_error=on_error,
46                                on_close=on_close)
47    ws.on_open = on_open
48    ws.run_forever()
49