代码如下所示:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from tornado.ioloop import IOLoop, PeriodicCallback
from tornado import gen
from tornado.websocket import websocket_connect
api_data = {
"method": "SUBSCRIBE",
"params": [
"btcusdt@trade"
],
"id": "BTCUSDT",
}
class Client(object):
def __init__(self, url, timeout):
self.url = url
self.timeout = timeout
self.ioloop = IOLoop.instance()
self.ws = None
self.connect()
PeriodicCallback(self.keep_alive, 20000).start()
self.ioloop.start()
@gen.coroutine
def connect(self):
print("trying to connect")
try:
self.ws = yield websocket_connect(self.url)
except Exception as e:
print("connection error")
else:
yield self.ws.write_message(json.dumps(api_data))
print("connected")
self.run()
@gen.coroutine
def run(self):
while True:
msg = yield self.ws.read_message()
if msg is None:
print("connection closed")
self.ws = None
break
else:
print(msg)
exit()
def keep_alive(self):
if self.ws is None:
self.connect()
else:
self.ws.write_message("keep alive")
if __name__ == "__main__":
client = Client("wss://stream.binance.com:9443/ws", 5)
运行时,它开始工作,但很快就会转储(1 分钟内)并出现错误
{"error":{"code":3,"msg":"Invalid JSON: expected value at line 1 column 1"}}
相同的程序适用于其他 websocket,此问题仅发生在 Binance API 上。 我不知道如何解决这个问题,非常感谢您的帮助! `
通过将
self.ws.write_message("keep alive")
更改为 self.ws.ping()
来修复