无法使用websocket:websocket._exceptions.websocketConnectionClosedCeption:套接字已关闭

发布于 2025-02-11 08:06:58 字数 2721 浏览 5 评论 0原文

谢谢您的入住!我对Websocket连接有一个疑问。

这是我用来订阅Exchange的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()

但是,当我在另一个名为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连接:

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]}))

您可以通过 https://bybybit-exchange.github.github.io/docs/docs/docs/linear/linear/# t-heartbeat

Thank you for checking in! I've got a question about the websocket connection.

Here's a websocket class I use to subscribe to an exchange's websocket, where the connection is established in self.connectWS_public() function.

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

However, when I test the connection in another file called test.py, I always encounter the following error:

  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.

Below is my test.py used to test the websocket connection:

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]}))

You may check the exchange API documentation via
https://bybit-exchange.github.io/docs/linear/#t-heartbeat

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

望喜 2025-02-18 08:06:58

我得到了解决方案的人:

通常,如果您遇到了类似的错误,则可能在建立连接后没有睡觉。

尝试添加:time.sleep(5)呼叫ws.run_forever()

这允许在向其发送任何请求之前成功连接Websocket连接。

Guys I have got the solution:

In general, if you have encountered a similar error like me, it's possible that you didn't sleep the program after establishing the connection.

Try to add: time.sleep(5) after calling ws.run_forever()

This allows the websocket connection to be successfully connected before sending any request to it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文