【问题标题】:websockets difference between ws.on and ws.onmessagews.on 和 ws.onmessage 之间的 websockets 区别
【发布时间】: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


    【解决方案1】:

    库WS 是WebSocket API 的包装器,因此“onmessage”在这里不起作用。

    【讨论】:

      猜你喜欢
      • 2020-10-10
      • 1970-01-01
      • 2011-11-29
      • 2012-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      • 2020-05-10
      相关资源
      最近更新 更多