nodejs websockets订阅多个频道

时间:2017-12-27 01:39:09

标签: node.js websocket redis socket.io

最终目标是让我的nodejs程序订阅多个渠道,提供实时财务信息并处理流数据。

在python中,可以使用functools / partial和websocket订阅多个频道。这允许一个python程序订阅多个通道。在我的情况下,我试图用nodejs / javascript做同样的事情。

Python websockets, subscribe to multiple channels

是否可以使用wesocket和其他包的组合在nodejs中执行类似的操作?

我下面的内容有效但它在一个输出中输出来自三个不同通道的流,这很难管理。



/*jshint esversion: 6 */

var sys = require('util');

const WebSocket = require('ws')
const wss = new WebSocket('wss://api.bitfinex.com/ws/')

wss.onopen = () => {
  console.log('Subscribing: BTCUSD');
  wss.send(JSON.stringify(
    {
      "event":"subscribe",
      "channel":"book",
      "pair":"BTCUSD",
      "prec":"P0",
      "freq":"F1"
    }
  ));
  console.log('Subscribing: LTCUSD');
  wss.send(JSON.stringify(
    {
      "event":"subscribe",
      "channel":"book",
      "pair":"LTCUSD",
      "prec":"P0",
      "freq":"F1"
    }
  ));
  console.log('Subscribing: LTCBTC');
  wss.send(JSON.stringify(
    {
      "event":"subscribe",
      "channel":"book",
      "pair":"LTCBTC",
      "prec":"P0",
            "freq":"F1"
    }
  ));
  console.log('Subscribing: ETHUSD');
  wss.send(JSON.stringify(
    {
      "event":"subscribe",
      "channel":"book",
      "pair":"ETHUSD",
      "prec":"P0",
            "freq":"F1"
    }
  ));
}

wss.onmessage = (msg) => {
  var response = JSON.parse(msg.data);
  var head = response["event"];
  var head_body = response[1];
  
  if ( head == "subscribed" ) {
    console.log("channelID = ", response["chanId"], " currency = ", response["pair"]);
  } else {
    console.log(msg.data);
  }
}




感谢对此的指导。我也在看socket.io。也许那可以做到吗?

0 个答案:

没有答案