js实现测试网速
实现测试网速的方法
使用 JavaScript 和 XMLHttpRequest
创建一个 XMLHttpRequest 对象,通过下载一个已知大小的文件并计算下载时间,从而估算网速。
function testSpeed() {
const fileSizeInBytes = 1024 * 1024; // 1MB 文件
const url = 'https://example.com/speedtestfile'; // 替换为实际文件 URL
const startTime = new Date().getTime();
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onprogress = function(e) {
if (e.lengthComputable) {
const elapsedTime = (new Date().getTime() - startTime) / 1000; // 秒
const speed = (e.loaded / elapsedTime) / 1024; // KB/s
console.log(`当前速度: ${speed.toFixed(2)} KB/s`);
}
};
xhr.onload = function() {
const endTime = new Date().getTime();
const duration = (endTime - startTime) / 1000; // 秒
const speed = (fileSizeInBytes / duration) / 1024; // KB/s
console.log(`平均速度: ${speed.toFixed(2)} KB/s`);
};
xhr.send();
}
使用 Fetch API 和 Performance API
利用 Fetch API 和 Performance API 提供的高精度时间戳,实现更精确的测速。
async function testSpeedWithFetch() {
const fileSizeInBytes = 1024 * 1024; // 1MB 文件
const url = 'https://example.com/speedtestfile'; // 替换为实际文件 URL
const startTime = performance.now();
try {
const response = await fetch(url);
const reader = response.body.getReader();
let receivedBytes = 0;
let chunks = [];
while (true) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
receivedBytes += value.length;
const elapsedTime = (performance.now() - startTime) / 1000; // 秒
const speed = (receivedBytes / elapsedTime) / 1024; // KB/s
console.log(`当前速度: ${speed.toFixed(2)} KB/s`);
}
const endTime = performance.now();
const duration = (endTime - startTime) / 1000; // 秒
const speed = (receivedBytes / duration) / 1024; // KB/s
console.log(`平均速度: ${speed.toFixed(2)} KB/s`);
} catch (error) {
console.error('测速失败:', error);
}
}
使用 WebSocket 测速
通过 WebSocket 发送和接收数据包,测量往返时间(RTT)和带宽。
function testSpeedWithWebSocket() {
const ws = new WebSocket('wss://example.com/speedtest'); // 替换为实际 WebSocket 服务
const testData = new ArrayBuffer(1024); // 1KB 测试数据
let startTime;
ws.onopen = function() {
startTime = performance.now();
ws.send(testData);
};
ws.onmessage = function(e) {
const endTime = performance.now();
const duration = endTime - startTime; // 毫秒
const speed = (testData.byteLength * 8 / duration) * 1000 / 1024; // Kbps
console.log(`速度: ${speed.toFixed(2)} Kbps`);
ws.close();
};
}
注意事项
- 确保测试文件足够大(至少 1MB),避免小文件测速不准确。
- 多次测试取平均值,减少网络波动影响。
- 考虑使用 CDN 或分布式的测试文件,确保地理位置不影响结果。
- 对于上传测速,可以使用类似方法通过 POST 请求发送数据。






