如何打开多个 WebSocket 流

How can I open multiple WebSocket streams

我正在尝试从 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 的实时数据。

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

根据 API documentation,可以只打开一个 Web 套接字,它会向您发送流列表中的数据,甚至只是所有流。只需像这样构造 URLs:

  • 特定流: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>