Using a websocket client as a class in python

前端 未结 8 1018
名媛妹妹
名媛妹妹 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:57

    I would like try this way:

    class FooClient(object):
        def __init__(self):
            def on_message(ws, message):
                print message
                # use 'self' variable to access other resource
                # handle message from websocket server like this
                self.handler.handle(message)
    
            def on_error(ws, error):
                print error
    
            def on_close(ws):
                print "### closed ###"
    
            def on_open(ws):
                ws.send("Hello %d" % i)
    
            # assign to 'self.handler'
            self.handler = FooHandler()
            # maybe there are another module should be initiated
            # ...
    
            websocket.enableTrace(True)
            self.ws = websocket.WebSocketApp("ws://echo.websocket.org:12300/foo",
                                             on_message = on_message,
                                             on_error = on_error,
                                             on_close = on_close)
    
        def run_forever(self):
            self.ws.run_forever()
    
        def close(self):
            """clean other resources"""
            pass
    

    Using inner function in method __init__(self) could avoid the problem that the arguments number of on_message(self, ws, message) method not match with the number of WebSocketApp provides to its argument on_message (class method has one more argument self).

    I have a handler above to handle the message, method close(self) to clean some resources if I have, run_forever(self) to run websocket.

提交回复
热议问题