将websocket客户端用作python中的类 [英] Using a websocket client as a class in python

查看:293
本文介绍了将websocket客户端用作python中的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用websockets访问某些数据,但是我真的无法绕过websockets文档中给出的示例。

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

我有此代码( https://pypi.org/project/websocket_client/ ),并希望将其转换为类。

I have this code (https://pypi.org/project/websocket_client/) and want to transform it into a class.

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

这个想法是将所有websocket功能都包含在其中一个类,这样我就可以创建该类的对象。

The idea is to have this all websocket functionality in a class so that I can just create an object of that class.

我试图开始这样做,但我什至无法通过:

I tried to start doing it but I cannot even get passed this:

class MySocket(object):
    def __init__(self):
        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 on_message(ws, message):
        print message

    def on_error(ws, error):
        print error

    def on_close(ws):
        print "### closed ###"

    def on_open(ws):
    ws.send("Hello %d" % i)

错误开始正确

推荐答案

包装中的 on_message 中说这是未解决的参考。匿名 lambda 函数内部的调用,以使用正确的 self 进行正确的调用:

Package the call inside an anonymous lambda function to achieve a proper call with the correct self:

class Client:
    def __init__(self, db, symbols):
        self.ws = websocket.WebSocketApp("wss://the.server.com/api",
                    on_message = lambda ws,msg: self.on_message(ws, msg),
                    on_error   = lambda ws,msg: self.on_error(ws, msg),
                    on_close   = lambda ws:     self.on_close(ws),
                    on_open    = lambda ws:     self.on_open(ws))

    def on_message(self, ws, message):
            msg = json.loads(message)
            print(msg)
    ...

这篇关于将websocket客户端用作python中的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆