1
votes

I'm trying to use websockets in python, and i previously asked a question about this. I quickly realized, though, that the way i was connecting to the server was meant for "one off" messages, while what i want to do needs to listen for notifications constantly. In the documentation for the python websocket client i can see the following code:

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):
    def run(*args):
        for i in range(3):
            time.sleep(1)
            ws.send("Hello %d" % i)
        time.sleep(1)
        ws.close()
        print "thread terminating..."
    thread.start_new_thread(run, ())


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()

The thing is, i'm still quite new to python, and i don't completely understand this code. Since it's example code, and does things that i don't need it to, i would like to understand how it works. I, for example, don't understand what the for loop is needed for, or what the __name__ and the __main__ at the bottom are.

Is there a better way?

Thanks, Sas :)

1

1 Answers

1
votes

The for loop is probably just an example since it will just print Hello 0, Hello 1 and Hello 2.

__name__ == "__main__" is true when the Python interpreter is running a module as the main program, which you can read more about here. Whenever that happens, it assigns what functions should be used on message, error and when the socket closes. And when that's done it runs the WebSocket forever.

So, to create your own long-lived WebSocket you can copy this example code and change the on_message, on_error, on_close and on_open functions to do what you want them to do whenever these events occour. on_message activates whenever a message is sent, on_error when an error occours, on_close when the WebSocket closes and on_open when the WebSocket opens.