Using a websocket client as a class in python

前端 未结 8 1021
名媛妹妹
名媛妹妹 2021-02-04 13:19

I\'m trying access some data using websockets, but I cannot really get around the examples given in the websockets documentation.

I have this code (https://pypi.org/proj

8条回答
  •  闹比i
    闹比i (楼主)
    2021-02-04 13:47

    Just updating the code written by other authors on this page, that worked for me. The problem is that in the event callback functions definition like on_message we should not use ws as parameter. self takes care of it and in the body of these event handler functions we should use self.ws

    class MySocket(object):
        def __init__(self):
            websocket.enableTrace(True)
            self.ws = websocket.WebSocketApp("ws://echo.websocket.org:12300/foo",
                                    on_message = self.on_message,
                                    on_error = self.on_error,
                                    on_close = self.on_close)
    
        
        def on_message(self, message):
            # if you want to send something use like this
            # self.ws.send()
            print message
    
        def on_error(self, error):
            print error
    
        def on_close(self):
            print "### closed ###"
    
        def on_open(self):
            self.ws.send("Hello Message")
    

提交回复
热议问题