我正在尝试连接到“ wss://api.huobi.pro/ws”。 连接后,我必须用消息“ {“ id”:“ wanbtc”,“ sub”:“ market.wanbtc.depth.step0”}“”
订阅频道 auto ws = new WebSocketSync;
ws->setIs_display_scan_speed(new bool(false));
QJsonObject json;
json["sub"] = "market.wanbtc.depth.step0";
json["id"] = "wanbtc";
ws->set_url("wss://api.huobi.pro/ws");
ws->set_register_message(QJsonDocument(json).toJson(QJsonDocument::Compact));
ws->open();
代码结果:
[Websocket] Current soket state: QAbstractSocket::ConnectingState
[Websocket] Current soket state: QAbstractSocket::ConnectedState
[Websocket] Connected to server "wss://api.huobi.pro/ws"
[Websocket] Send message to server "{\"id\":\"wanbtc\",\"sub\":\"market.wanbtc.depth.step0\"}"
但是在套接字不发送任何数据之后
类似的代码可在node.js上运行
const moment = require('moment');
const WebSocket = require('ws');
const pako = require('pako');
const WS_URL = 'wss://api.huobi.pro/ws';
var orderbook = {};
exports.OrderBook = orderbook;
function handle(data) {
console.log('received', data.ch, 'data.ts', data.ts, 'crawler.ts', moment().format('x'));
let symbol = data.ch.split('.')[1];
let channel = data.ch.split('.')[2];
switch (channel) {
case 'depth':
orderbook[symbol] = data.tick;
//console.log(data.tick);
break;
}
}
function subscribe(ws) {
var symbols = ['wanbtc'];
for (let symbol of symbols) {
var message = JSON.stringify({
"sub": `market.${symbol}.depth.step0`,
"id": `${symbol}`
});
console.log('send to ws ' + message);
ws.send(message);
}
}
function init() {
var ws = new WebSocket(WS_URL);
ws.on('open', () => {
console.log('connect to ' + WS_URL);
subscribe(ws);
});
ws.on('message', (data) => {
let text = pako.inflate(data, {
to: 'string'
});
let msg = JSON.parse(text);
if (msg.tick) {
// console.log(msg);
handle(msg);
}
});
}
init();
可能是什么原因?在node.js上工作,而不在Qt上工作。是否需要找到QWebsocket的替代产品?
修改1: WebSocketSync.cpp
WebSocketSync::WebSocketSync()
{
connect(&m_socket, &QWebSocket::connected, this, [=]{
qDebug() << "[Websocket] Connected to server" << m_socket.request().url().toString();
if (m_is_need_to_register_channel) {
qDebug() << "[Websocket] Send message to server" << m_register_message;
m_socket.sendTextMessage(m_register_message);
}
});
connect(&m_socket, &QWebSocket::textMessageReceived, this, [=](const QString & message) {
qDebug() << message;
});
}
void WebSocketSync::set_url(const QString &url)
{
// qDebug() << "[Websocket] Server url setted:" << url;
m_url.setUrl(url);
}
void WebSocketSync::set_register_message(const QString &url)
{
// qDebug() << "[Websocket] Register message setted:" << url;
m_is_need_to_register_channel = true;
m_register_message = url;
}
void WebSocketSync::open()
{
// qDebug() << "[Websocket] Open url:" << m_url;
m_socket.open(m_url);
}
答案 0 :(得分:0)
原因是服务器发送了二进制数据。我需要为此连接使用QWebSocket::binaryMessageReceived
。
现在我需要弄清楚如何处理二进制数据(\ x1F \ x8B \ b \ x00 \ x00)