最近在写一个项目,需要多线程请求WebSocket接口,但是因为WebSocket代码里有全局变量,导致多线程返回结果错误。所以在想怎么才能把外部参数传入on_open()、on_message()这些方法中,花了我一天时间,找遍全网才解决。在此记录。
直接上代码。
import ssl
import websocket
import _thread as thread
class WebsocketClient(object):
"""docstring for WebsocketClient"""
def __init__(self, address, send_message):
super(WebsocketClient, self).__init__()
self.address = address
self.send_message = send_message
self.recv = None
def on_message(self, ws, message):
self.recv = message
print("on_client_message:", self.recv)
def on_error(self, ws, error):
print("### error:", error)
def on_close(self, ws):
print("### closed ###")
def on_open(self, ws):
print("on open")
def run(*args):
self.ws.send(self.send_message)
print(self.send_message)
# self.ws.close()
thread.start_new_thread(run, ())
def get_message(self):
return self.recv
def run(self):
websocket.enableTrace(False)
self.ws = websocket.WebSocketApp(self.address,
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(sslopt={"cert_reqs": ssl.CERT_NONE})
if __name__ == '__main__':
ws_client = WebsocketClient("ws://121.40.165.18:8800", 'hello')
ws_client.run()
print(ws_client.get_message())
在初始化的时候,把想要传的参数放进去,无论是外部向内部传参,还是内部向外部传参,都可以直接调用。
参考:
链接: python3 websocket客户端.
链接: WebSocket 在线测试 v13.
链接: Python websocket 模块 WebSocketApp 长连接方法新老版本不兼容.