Using a websocket client as a class in python

前端 未结 8 1022
名媛妹妹
名媛妹妹 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条回答
  •  借酒劲吻你
    2021-02-04 13:55

    The Self makes those methods as Class methods , Got this one working as the on_error/message/close methods signature will get satisfied if called by self as will refer to the class itself .

     class MySocket(object):
       def __init__(self,x):
         websocket.enableTrace(True)
         ## Only Keep the object Initialisation here  
         self.x=x
         self.ws=None
    
         # call This method from a Object and it will create and run the websocket 
        def ws_comm(self):
            self.ws = websocket.WebSocketApp(self.WS_URL,on_message = 
            self.on_message,on_error =self.on_error,on_close = self.on_close)
            self.ws.on_open = self.on_open
            self.ws.run_forever()
    
        def on_error(self,ws, error):
            print "onError", error
    
        def on_close(self,ws):
           print "onClosed"
    
        #Send some message on open 
        def on_open(self,ws):
           self.ws.send(json.dumps(register_msg))
    
        def on_message(self,ws, msg):
           self.ws.send(json.dumps(msg))
    
    
     user1=Userapp('x')
     user1.ws_comm()
    

提交回复
热议问题