python 无法使用WebSocket:WebSocket,_异常,网络套接字连接关闭异常:套接字已关闭

gcuhipw9  于 2022-12-21  发布在  Python
关注(0)|答案(1)|浏览(798)

感谢您的登记!我有一个关于WebSocket连接的问题。
下面是一个WebSocket类,我用它来订阅交换机的websocket,其中连接是在self.connectWS_public()函数中建立的。

from datetime import datetime as dt
import threading
import websocket
import json
import time

class Bybit_WS_test():

    def __init__ (self):
        self.api_url_public = 'wss://stream.bybit.com/realtime_public'
        self.api_url_private = 'wss://stream-testnet.bybit.com/realtime_private'
        self.api_key = ''
        self.api_secret = ''

        self.ping_interval = 20
        self.ping_timeout = 10

        self.ws_public = None
        self.ws_private = None

        return

    def on_message(self, ws, message):
        data = json.loads(message)
        print('Received message:')
        print(data)

    def on_error(self, ws, error):
        print(f'webscoket error: {error}')
    
    def on_close(self, ws):
        print("Closing websocket connection...")

    def on_pong(self, ws, message):
        print('Received pong')
        print(message)

    def on_open(self, ws):
        print('Websocket opened')

    def on_ping(self, message):
        dt_string = dt.now().strftime("%d/%m/%Y %H:%M:%S")
        print(message)
        print(f'Received ping @ {dt_string}')

    def connectWS_public(self):

        self.ws_public = websocket.WebSocketApp(
            url = self.api_url_public,
            on_message = self.on_message,
            on_error = self.on_error,
            on_ping= self.on_ping,
            on_pong= self.on_pong,
            on_open= self.on_open
        )
        self.wst_public = threading.Thread(target=lambda: self.ws_public.run_forever(ping_interval=self.ping_interval, ping_timeout=self.ping_timeout))
        self.wst_public.daemon = True
        self.wst_public.start()

但是,当我在另一个名为www.example.com的文件中测试连接时test.py,总是遇到以下错误:

File "/Users/rickycheng/Desktop/pair-trading-bot/venv/lib/python3.7/site-packages/websocket/_socket.py", line 143, in send
    raise WebSocketConnectionClosedException("socket is already closed.")
websocket._exceptions.WebSocketConnectionClosedException: socket is already closed.

下面是test.py用来测试WebSocket连接的www.example.com:

from Bybit_api.Bybit_ws import Bybit_WS_test
import json

if __name__ == '__main__':
    x = Bybit_WS_test()
    x.connectWS_public()

    while (x.ws_public.sock):
        print(True)
        topic = "orderBookL2_25.BTCUSD"
        x.ws_public.send(json.dumps({"op": "subscribe",'args':[topic]}))

您可以通过www.example.com查看Exchange API文档https://bybit-exchange.github.io/docs/linear/#t-heartbeat

fhg3lkii

fhg3lkii1#

伙计们,我有办法了:
一般来说,如果您遇到了类似的错误,像我一样,这是可能的,你没有睡眠的程序后,建立连接。
尝试在调用ws.run_forever()后添加:time.sleep(5)
这允许WebSocket连接在向其发送任何请求之前成功连接。

相关问题