js实现ping
JavaScript 实现 Ping 功能
在 JavaScript 中实现 Ping 功能通常需要借助 Web API 或第三方服务,因为浏览器环境限制了直接 ICMP 请求。以下是几种常见方法:
使用 Image 对象检测网络延迟
通过加载一个微小图片并计算时间差来模拟 Ping:
function ping(url, callback) {
const start = new Date().getTime();
const img = new Image();
img.onload = function() {
const end = new Date().getTime();
const latency = end - start;
callback(null, latency);
};
img.onerror = function() {
callback(new Error('Ping failed'));
};
img.src = url + '?t=' + start; // 添加时间戳避免缓存
}
使用 Fetch API 测量延迟
现代浏览器可以使用 Fetch API 测量 HTTP 请求延迟:

async function ping(url) {
const start = performance.now();
try {
await fetch(url, { method: 'HEAD', cache: 'no-store' });
const latency = performance.now() - start;
return Math.round(latency);
} catch (error) {
return -1; // 表示失败
}
}
使用 WebSocket 测量延迟
对于需要实时通信的场景,WebSocket 可以提供更精确的延迟测量:
function wsPing(url, callback) {
const socket = new WebSocket(url);
const start = Date.now();
socket.onopen = function() {
socket.send('ping');
};
socket.onmessage = function() {
const latency = Date.now() - start;
callback(null, latency);
socket.close();
};
socket.onerror = function() {
callback(new Error('WebSocket error'));
};
}
使用第三方 Ping API
某些服务提供专门的 Ping API 端点:

async function apiPing() {
const response = await fetch('https://api.example.com/ping');
const data = await response.json();
return data.latency;
}
注意事项
浏览器安全策略限制真正的 ICMP Ping,上述方法都是基于 HTTP/WebSocket 的近似实现
跨域请求可能被阻止,确保目标服务器支持 CORS 或使用同源 URL
对于 Node.js 环境,可以使用 net 或 dgram 模块实现更底层的 Ping 功能






