【发布时间】:2018-01-10 19:03:20
【问题描述】:
我在 javascript 中使用 websockets 连接到 API 并读取一些数据。
代码如下:
function processHUOBIAPI(client,exchange_name,exchange_wss,exchange_symbol)
{
// Define constants
const WebSocket = require('ws');
const pako = require('pako');
// Open connection once one is established
var wss = new WebSocket(exchange_wss);
wss.onopen = () =>
{
// Send request to subscribe
var symbol = exchange_symbol.toLowerCase()
wss.send(JSON.stringify(
{
"sub": "market." + symbol + ".kline.1min",
"id": symbol
}
));
};
// Parse channel information and send to Redis
wss.onmessage = (data) =>
{
//typedef data;
console.log("Receive message", data);
let text = pako.inflate(data, {
to: 'string'
});
mssg = JSON.parse(text);
if (mssg.ping) {
wss.send(JSON.stringify({
pong: mssg.ping
}));
} else if (mssg.tick) {
console.log(mssg);
//handle(msg);
} else {
console.log(text);
}
}
在这种情况下,我得到一个错误:
..../node_modules/pako/lib/inflate.js:384 if (inflator.err) { throw inflator.msg || msg[inflator.err]; } ^ 未知的压缩方法
如果我将 "wss.onmessage = (data) =>" 更改为 "wss.on ('message', (data) => {" 并删除额外的 ')' 代码完美运行。
wss.on 和 wss.onmessage 有什么区别?
这个新手非常感谢任何指导。如果这是一个愚蠢的,请提前道歉....
【问题讨论】:
标签: javascript node.js websocket