简体   繁体   English

Websocket 断开连接

[英]Websocket Disconnection

I am using python websocket-client to subscribe to kraken exchange websocket.我正在使用 python websocket-client 订阅 kraken 交换 websocket。 The systems works fine initially for a day or two but then it start facing disconnection from cloudflare with error系统最初可以正常运行一两天,但随后开始面临与 cloudflare 的断开连接并出现错误

GET / HTTP/1.1
Upgrade: websocket
Host: ws.kraken.com
Origin: http://ws.kraken.com
***

and after many reattempts by the system websockets gives the error
*** error from callback <function on_close at 0x000001F33E2CBAC0>: maximum recursion depth exceeded while calling a Python object

My implementation我的实现

def on_close(ws, close_status_code, close_msg):
    log.info("Connection Closed:" + str(close_status_code)+" " + str(close_msg))
    print("Connection Closed:" + str(close_status_code)+" " + str(close_msg))
    print("Retry : %s" % time.ctime())
    time.sleep(10)
    print("restarting bot")
    connect_websocket()  # retry per 10 seconds


def on_open(ws):
    # print(symbol)
    print('connection established')

    string = {"event": "subscribe", "pair": ["ADA/USD", "BCH/USD", "DOT/USD", "ENJ/USD", "ETC/USD", "ETH/USD", "FIL/USD", "GNO/USD", "KSM/USD", "LTC/USD", "OMG/USD", "SC/USD", "SOL/USD", "DOGE/USD", "XRP/USD", "SHIB/USD", "AXS/USD", "BAL/USD", "COMP/USD", "CRV/USD", "CQT/USD", "DASH/USD", "EOS/USD", "EWT/USD", "GHST/USD", "GRT/USD", "KAR/USD", "LINK/USD", "LPT/USD", "LSK/USD", "MANA/USD", "MINA/USD", "MOVR/USD", "OXT/USD", "QTUM/USD", "SAND/USD", "TRX/USD", "XLM/USD", "XMR/USD", "ZEC/USD", "BTC/USD"], "subscription": {"interval": 240, "name": "ohlc"}}
    ws.send(json.dumps(string))


def on_message(ws, message):
    print(message)
    message = json.loads(message, parse_float=decimal)
    try:
       if message["event"] == 'heartbeat':
        return
    except:
        log.info(message)



def connect_websocket(): ## TO CONNECT TO WEBSOCKET, CALL ON EACH bot restart command
    websocket.enableTrace(True, log)
    global ws

    ws = websocket.WebSocketApp("wss://ws.kraken.com/", on_open=on_open,
                                                        on_close=on_close,
                                                        on_message = on_message)
    print("symbol  timeframe ", str(240))
    ws.run_forever()

Try this in the beginning of the script, worked for me在脚本的开头试试这个,对我有用

import gevent.monkey
gevent.monkey.patch_all()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM