如何打开多个WebSocket流

时间:2019-01-01 17:09:46

标签: javascript arrays for-loop websocket binance

我正在尝试从Binance WebSocket API流式传输数据,我一次只能处理一个符号。

if ("WebSocket" in window) {
            //open websocket
            var symbols = getSymbol();
            //console.log(symbols);

            symbols.forEach(function(entry) {
              console.log(entry);
            })

            var ws = new WebSocket("wss://stream.binance.com:9443/ws/btcusdt@miniTicker")

            ws.onopen = function() {
                console.log("Binance connected...");
            };

            ws.onmessage = function(evt) {
                var r_msg = evt.data;
                var jr_msg = JSON.parse(r_msg);   
            }

            ws.onclose = function() {
                console.log("Binance disconnected");
            }
        } else {
            alert("WebSocket is NOT supported");
        }

var symbols = getSymbol();行创建了一个431个符号的数组,我的逻辑(以及我要实现的目标)是将new websocket()添加到forEach并从所有货币流式传输价格数据对。

我不确定这是否完全可行或有什么更好的解决方案,但我希望通过api流式传输并显示实时数据。

2 个答案:

答案 0 :(得分:1)

您关于将new WebSocket()放入for-each的想法应该可行。然而, 我不确定是否允许您从同一选项卡打开数百个Web套接字,并且还可能存在一些与此相关的性能问题。

根据API documentation,可以仅打开一个Web套接字,该套接字将向您发送来自流列表甚至所有流的数据。只需构建如下URL:

  • 特定流:wss://stream.binance.com:9443 / ws / stream1 / stream2 / stream3
  • 所有流:wss://stream.binance.com:9443 / ws /!miniTicker @ arr

这里是一个代码样本,其中考虑了这些因素。默认情况下,此代码对所有流使用URL,但也有使用特定流的代码(注释掉)。

  let streams = [
    "ethbtc@miniTicker","bnbbtc@miniTicker","wavesbtc@miniTicker","bchabcbtc@miniTicker",
    "bchsvbtc@miniTicker","xrpbtc@miniTicker","tusdbtc@miniTicker","eosbtc@miniTicker",
    "trxbtc@miniTicker","ltcbtc@miniTicker","xlmbtc@miniTicker","bcptbtc@miniTicker",
    "adabtc@miniTicker","zilbtc@miniTicker","xmrbtc@miniTicker","stratbtc@miniTicker",
    "zecbtc@miniTicker","qkcbtc@miniTicker","neobtc@miniTicker","dashbtc@miniTicker","zrxbtc@miniTicker"
  ];

  let trackedStreams = [];

  //let ws = new WebSocket("wss://stream.binance.com:9443/ws/" + streams.join('/'));
  let ws = new WebSocket("wss://stream.binance.com:9443/ws/!miniTicker@arr");

  ws.onopen = function() {
      console.log("Binance connected...");
  };

  ws.onmessage = function(evt) {
    try {
      let msgs = JSON.parse(evt.data);
      if (Array.isArray(msgs)) {
        for (let msg of msgs) {
          handleMessage(msg);
        }
      } else {
        handleMessage(msgs)
      }
    } catch (e) {
      console.log('Unknown message: ' + evt.data, e);
    }
  }

  ws.onclose = function() {
    console.log("Binance disconnected");
  }

  function handleMessage(msg) {
    const stream = msg.s;
    if (trackedStreams.indexOf(stream) === -1) {
      document.getElementById('streams').innerHTML += '<br/>' + stream + ': <span id="stream_' + stream + '"></span>';
      trackedStreams.push(stream);
      document.getElementById('totalstreams').innerText = trackedStreams.length;
    }

    document.getElementById('stream_' + stream).innerText = msg.v;
  }
<span id="totalstreams"></span> streams tracked<br/>
Total traded base asset volume:<br/>
<div id="streams"></div>

答案 1 :(得分:0)

简单快速的代码在这里,

例如多个流,如“bitcoin-usdt”和“ethereum-usdt”:

wss://stream.binance.com:9443/ws/stream?streams=btcusdt@miniTicker/ethusdt@miniTicker/

您可以使用 / 分隔符添加流