You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多WebSocket连接致浏览器卡顿,如何通过ID获取币安实时多币价?

优化Binance加密货币实时价格的WebSocket连接方案

当前实现中,每种加密货币都单独创建一条WebSocket连接,导致浏览器性能下降、出现卡顿警告。需求是通过不同ID的<input>(如#btc-price、#ltc-price)展示多种币种的实时价格,同时减少WebSocket连接数提升性能。

优化核心思路

利用Binance提供的**合并流(Combined Streams)**功能,仅建立1条WebSocket连接即可订阅多个币种的交易数据流,从根源上减少连接数带来的资源消耗;同时通过统一的配置和逻辑处理,实现代码复用与可扩展性。

优化后的代码实现

HTML

保持原有输入框结构,可按需新增币种输入框:

<div class="wrap">
  <input type="text" id="btc-price" placeholder="BTC-USDT">
  <input type="text" id="ltc-price" placeholder="LTC-USDT">
  <!-- 新增币种只需添加对应input,例如: -->
  <!-- <input type="text" id="eth-price" placeholder="ETH-USDT"> -->
</div>

CSS

保留原有样式并优化间距:

.wrap {
  width: 250px;
  margin: 0 auto;
  padding-top: 1em;
}

input {
  width: 225px;
  height: 52px;
  font-size: 20px;
  text-align: center;
  margin: 8px 0;
}

JavaScript

// 配置监控币种:键为Binance流标识,值为对应input的ID和历史价格存储
const currencyMap = {
  'btcusdt@trade': {
    inputId: 'btc-price',
    lastPrice: null,
    inputElement: null
  },
  'ltcusdt@trade': {
    inputId: 'ltc-price',
    lastPrice: null,
    inputElement: null
  }
  // 新增币种只需添加配置项,例如:
  // 'ethusdt@trade': {
  //   inputId: 'eth-price',
  //   lastPrice: null,
  //   inputElement: null
  // }
};

// 预加载所有DOM元素,避免重复查询
Object.values(currencyMap).forEach(item => {
  item.inputElement = document.getElementById(item.inputId);
});

// 生成合并流URL
const streamList = Object.keys(currencyMap).join('/');
const wsUrl = `wss://stream.binance.com:9443/stream?streams=${streamList}`;

// 建立单个WebSocket连接
const socket = new WebSocket(wsUrl);

// 统一处理消息
socket.onmessage = (event) => {
  const data = JSON.parse(event.data);
  const streamKey = data.stream;
  const currencyItem = currencyMap[streamKey];
  
  if (!currencyItem) return;

  const currentPrice = parseFloat(data.data.p).toFixed(9);
  
  // 更新价格颜色
  currencyItem.inputElement.style.color = !currencyItem.lastPrice || currencyItem.lastPrice === currentPrice
    ? 'black'
    : currentPrice > currencyItem.lastPrice ? 'green' : 'red';
  
  // 更新输入框价格
  currencyItem.inputElement.value = currentPrice;
  currencyItem.lastPrice = currentPrice;
  
  // 触发计算器变更事件
  $('.ChangeCalulator').change();
};

// 可选:处理连接异常与重连(示例)
socket.onerror = (err) => {
  console.error('WebSocket连接错误:', err);
};

socket.onclose = () => {
  console.log('连接断开,3秒后尝试重连...');
  setTimeout(() => window.location.reload(), 3000);
};

优化优势

  • 资源减负:从N条连接缩减为1条,彻底解决多连接导致的浏览器卡顿问题
  • 易扩展:新增币种仅需在currencyMap中添加配置,无需重复编写WebSocket逻辑
  • 性能提升:预缓存DOM元素,避免每次消息回调都执行DOM查询操作
  • 逻辑统一:所有币种的价格更新逻辑复用,减少代码冗余

内容的提问来源于stack exchange,提问作者Vivek Vivi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 09:51:27