萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

純 JavaScript 實現 Ping 功能:基於 Image 載入的網絡可達性檢測

原理說明

瀏覽器**無法發送真正的 ICMP Ping**(需原始套接字權限)。替代方案:請求目標服務器的一個極小資源(如 1x1 像素圖片、favicon、空 API),通過 **HTTP 請求是否成功** 推斷網絡可達性與延遲。

核心實現

/**
 * HTTP 偽 Ping
 * @param {string} target - 目標域名或 IP(含端口),如 'example.com' 或 '192.168.1.1:80'
 * @param {Object} options
 * @param {number} options.timeout - 超時毫秒數,默認 3000
 * @param {string} options.path - 請求路徑,默認 '/favicon.ico'(通常最小、有緩存)
 * @param {boolean} options.https - 是否強制 HTTPS,默認 false
 * @returns {Promise<{alive: boolean, latency: number, error?: Error}>}
 */
function httpPing(target, options) {
  options = Object.assign({
    timeout: 3000,
    path: '/favicon.ico',
    https: false
  }, options);

  return new Promise(function (resolve) {
    var start = performance.now();
    var img = new Image();
    var settled = false;
    var url = (options.https ? 'https:' : 'http:') + '//' + target + options.path + '?t=' + start; // 防緩存

    function finish(alive, err) {
      if (settled) return;
      settled = true;
      clearTimeout(timer);
      img.onload = img.onerror = null;
      img.src = ''; // 釋放連接
      resolve({ alive: alive, latency: performance.now() - start, error: err });
    }

    img.onload = function () { finish(true); };
    img.onerror = function () { finish(false, new Error('HTTP error or CORS blocked')); };

    var timer = setTimeout(function () { finish(false, new Error('Timeout')); }, options.timeout);
    img.src = url;
  });
}

// 使用
httpPing('www.google.com', {timeout: 2000, https: true})
  .then(function (res) {
    console.log(res.alive ? '🟢 可達 (' + res.latency.toFixed(0) + 'ms)' : '🔴 不可達', res.error || '');
  });

進階:多目標並發測速,選擇最優節點

async function findFastestNode(hosts, options) {
  var results = await Promise.all(hosts.map(function (host) {
    return httpPing(host, options).then(function (r) { return {host: host, ...r}; });
  }));

  var alive = results.filter(function (r) { return r.alive; });
  alive.sort(function (a, b) { return a.latency - b.latency; });

  return {
    fastest: alive[0] || null,
    all: results
  };
}

// 使用
var cdnNodes = ['cdn1.example.com', 'cdn2.example.com', 'cdn3.example.com'];
findFastestNode(cdnNodes, {timeout: 3000, https: true}).then(function (res) {
  console.log('最快節點:', res.fastest);
  // 動態切換 CDN 域名
  if (res.fastest) switchCDN(res.fastest.host);
});

關鍵限制與避坑

限制說明應對
非真實 ICMP只能測 HTTP/HTTPS 端口可達性業務層面通常足夠(CDN、API 端點)
CORS 限制跨域圖片請求不攜帶 Cookie,但 `onerror` 會觸發(即使 200 OK 也可能因 CORS 觸發 error)用同域資源、或配置 `Access-Control-Allow-Origin: *` 的專用 Ping 端點
緩存干擾瀏覽器緩存導致延遲極低(非真實網絡延遲)URL 加隨機查詢參數 `?t=timestamp`
瀏覽器並發限制同域名並發連接數限制(HTTP/1.1: 6,HTTP/2: 100+)並發測速時注意域名分片
混合內容HTTPS 頁面請求 HTTP 圖片被阻擋統一用 HTTPS,或專用 HTTP Ping 端點
Service Worker 攔截SW 可能返回緩存或離線頁,導致誤判Ping URL 加 `?bypass-sw=1`,SW 中判斷跳過

生產級增強:專用 Ping 端點

// 後端(Node.js/Express 示例)
app.get('/ping', (req, res) => {
  res.set('Cache-Control', 'no-store, no-cache, must-revalidate');
  res.set('Access-Control-Allow-Origin', '*');
  res.send('pong'); // 或返回 JSON {time: Date.now()}
});

// 前端
httpPing('api.example.com', {path: '/ping', https: true, timeout: 1500});

Web Worker 版:不阻塞主線程

// ping-worker.js
self.onmessage = function (e) {
  var {target, options} = e.data;
  httpPing(target, options).then(function (res) {
    self.postMessage({target, ...res});
  });
};

// 主線程
var worker = new Worker('ping-worker.js');
worker.onmessage = function (e) { console.log('Worker 結果:', e.data); };
worker.postMessage({target: 'cdn.example.com', options: {https: true}});

結語

瀏覽器端「Ping」本質是 **HTTP 探活**。掌握 Image 載入時序、緩存繞過、CORS 陷阱、超時控制、並發限制,即可構建可靠的網絡質量檢測、CDN 智能選擇、離線檢測等功能。現代專案建議封裝為 NetworkQualityMonitor 服務,定期採樣上報,指導自適應碼率、預加載策略。

copyright © 萬盛學電腦網 all rights reserved