在web worker或service worker中运行websocket - javascript

问题描述 投票:1回答:1

我有9个来自不同站点的websocket连接,正在用数据更新DOM。目前,我正在连接到所有的websocket并监听所有的websocket,并通过函数调用更新数据。

我面临的问题是,有许多websocket连接,存在内存和CPU使用问题。我如何使用服务工作者和web工作者来优化这么多的websocket连接?

async function appendGatePublicTickersData(e) {
  if (e.event == "update" && e.result[0].contract == "BTC_USD") {
    if ('total_size' in e.result[0]) {
      $(".gate-btc-open-interest").html(commaNumber(e.result[0].total_size))
      if ('last' in e.result[0]) {
        $(".gate-btc-open-value").html(commaNumber(customFixedRounding((e.result[0].total_size / e.result[0].last), 4)))
      }
    }

    if ('volume_24h_usd' in e.result[0]) {
      $(".gate-btc-24-volume").html(commaNumber(e.result[0].volume_24h_usd))
    }

    if ('volume_24h_btc' in e.result[0]) {
      $(".gate-btc-24-turnover").html(commaNumber(e.result[0].volume_24h_btc))
    }

    if ('funding_rate' in e.result[0]) {
      var fundingRateBtcGate = customFixedRounding(e.result[0].funding_rate * 100, 4)
      $(".public-gate-btc-funding").html(fundingRateBtcGate)
    }

    if ('funding_rate_indicative' in e.result[0]) {
      var predictedRateBtcGate = customFixedRounding(e.result[0].funding_rate_indicative * 100, 4)
      $(".public-gate-btc-predicted").html(predictedRateBtcGate)
    }
  }
}

var pubGateWs = new WebSocket("wss://fx-ws.gateio.ws/v4/ws/btc");

pubGateWs.addEventListener("open", function() {
  pubGateWs.send(JSON.stringify({
    "time": 123456,
    "channel": "futures.tickers",
    "event": "subscribe",
    "payload": ["BTC_USD", "ETH_USD"]
  }))
});

pubGateWs.addEventListener("message", function(e) {
  e = JSON.parse(e.data)
  appendGatePublicTickersData(e)
});

pubGateWs.addEventListener("close", function() {});
javascript jquery websocket service-worker web-worker
1个回答
1
投票

由于您使用的是 Web Sockets,因此最好使用一个名为 "Web Sockets "的应用程序。SharedWorker 为您的Web Sockets创建一个新的线程。正常的 WebWorker 和a SharedWorker 是指当加载页面时,Web Worker 将在每个标签页或浏览器中创建一个新的会话,而共享 Worker 将在每个标签页中使用相同的会话。因此,您的所有标签页或窗口都将拥有相同的 Worker 和相同的 Web Socket 连接来工作。

如果数据更新非常频繁(每秒超过60次),并且每次更新DOM时都要更新,那么使用 requestAnimationFrame 方法来节制DOM的更新量,它将等待下一个重绘周期才更新DOM中的新内容,大约每秒60次,即60FPS。它将等待下一个重绘周期才更新DOM的新内容,大约是每秒60次,即60FPS。

这样的实现会像下面的例子。

主线程: Web Worker.

function appendGatePublicTickersData(e) {
  ...
}

// Create shared worker.
const webSocketWorker = new SharedWorker('web-sockets-worker.js');

// Function to send new data from main thread to worker.
function updateData(data) {
  webSocketWorker.port.postMessage(data);
}

// Event to listen for incoming data from the worker and update the DOM.
webSocketWorker.port.addEventListener('message', ({ data }) => {
  requestAnimationFrame(() => {
    appendGatePublicTickersData(data);
  });
});

// Initialize the port connection.
webSocketWorker.port.start();

Web Worker。

// Listen for starting of shared worker.
self.addEventListener('connect', { ports } => {

  // Select the port to listen to.
  const port = ports[0];

  const pubGateWs = new WebSocket("wss://fx-ws.gateio.ws/v4/ws/btc");

  pubGateWs.addEventListener("open", () => {
    pubGateWs.send(JSON.stringify({
      "time": 123456,
      "channel": "futures.tickers",
      "event": "subscribe",
      "payload": ["BTC_USD", "ETH_USD"]
    }))
  });

  // Send data from Web Socket to main thread.
  pubGateWs.addEventListener("message", ({ data }) => {
    port.postMessage(JSON.parse(data));
  });

  // Receive data from main thread and send to Web Socket.
  port.addEventListener('message', ({ data }) => {
    pubGateWs.send(JSON.stringify(data));
  });

  // Start the port broadcasting.
  port.start();

});

旁白:你的 appendGatePublicTickersData 不使用 await 关键字,所以它不一定是一个 async 职能。

© www.soinside.com 2019 - 2024. All rights reserved.