js实现ping
在JavaScript中实现类似Ping的功能通常需要借助WebSocket、HTTP请求或第三方API,因为浏览器端的JavaScript无法直接发送ICMP请求(传统Ping协议)。以下是几种常见的方法:
使用HTTP请求模拟Ping
通过测量从发送HTTP请求到接收响应的时间来模拟Ping的延迟。这种方法依赖目标服务器支持HTTP/HTTPS。

async function httpPing(url, count = 4) {
const results = [];
for (let i = 0; i < count; i++) {
const start = performance.now();
try {
await fetch(url, { method: 'HEAD', mode: 'no-cors' });
const duration = Math.round(performance.now() - start);
results.push({ seq: i + 1, time: duration, status: 'success' });
} catch (e) {
results.push({ seq: i + 1, time: null, status: 'failed' });
}
}
return results;
}
// 使用示例
httpPing('https://example.com').then(console.log);
使用WebSocket检测延迟
如果目标服务支持WebSocket,可以通过建立连接的时间估算延迟:

function wsPing(url, count = 4) {
const results = [];
let counter = 0;
return new Promise((resolve) => {
const runTest = () => {
const start = performance.now();
const ws = new WebSocket(url);
ws.onopen = () => {
const duration = Math.round(performance.now() - start);
results.push({ seq: counter + 1, time: duration, status: 'success' });
ws.close();
if (++counter < count) setTimeout(runTest, 1000);
else resolve(results);
};
ws.onerror = () => {
results.push({ seq: counter + 1, time: null, status: 'failed' });
if (++counter < count) setTimeout(runTest, 1000);
else resolve(results);
};
};
runTest();
});
}
// 使用示例(需真实WebSocket地址)
wsPing('wss://echo.websocket.org').then(console.log);
通过第三方API实现
部分服务提供Ping功能的API封装(如cloudflare或自定义后端):
async function apiPing(apiUrl, target, count = 4) {
const response = await fetch(`${apiUrl}?target=${target}&count=${count}`);
return await response.json();
}
// 使用示例(需自行部署或使用现有API)
apiPing('https://your-api.com/ping', 'example.com').then(console.log);
注意事项
- 浏览器安全策略限制:跨域请求需目标服务器配置CORS。
- 精度差异:HTTP/WebSocket延迟包含TCP握手时间,不同于ICMP Ping。
- 服务器支持:目标必须开放对应协议端口(80/443/ws等)。
对于Node.js环境,可使用net模块或ping包实现真实ICMP Ping:
// Node.js示例(需安装ping包)
const ping = require('ping');
ping.promise.probe('example.com').then(res => console.log(res.time));






