gpt4 book ai didi

python - 在 python 中使用 websocket 客户端作为类

转载 作者:太空狗 更新时间:2023-10-29 21:20:54 25 4
gpt4 key购买 nike

我正在尝试使用 websockets 访问一些数据,但我无法真正理解 websockets 文档中给出的示例。

我有这段代码 ( https://pypi.org/project/websocket_client/ ) 并且想将它转换成一个类。

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 功能都放在一个类中,这样我就可以创建该类的一个对象。

我试着开始做,但我什至无法通过这个:

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 中开始,表示这是一个“ Unresolved 引用”。

最佳答案

将调用打包到匿名 lambda 函数中,以使用正确的 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)
...

关于python - 在 python 中使用 websocket 客户端作为类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26980966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com