我在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
如果(inflator.err){抛出inflator.msg || msg [inflator.err]; }
^
未知压缩方式
如果我将“ wss.onmessage =(data)=>”更改为“ wss.on('message',(data)=> {”并删除多余的')',则代码可以正常工作。
wss.on和wss.onmessage有什么区别?
新手,因此感谢任何指导。如果这很愚蠢,请提前道歉....
最佳答案
库WS是WebSocket API的包装,因此“ onmessage”在这里不起作用。
关于javascript - ws.on和ws.onmessage之间的websockets区别,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48044294/