如何计算服务器端node.js中的互联网速度,从客户端,我在查询字符串中发出http请求时发送当前时间戳。
客户端代码
var image = document.createElement("img");
image.width = 1;
image.height = 1;
image.src = url+"?"+new Date().getTime();
网址如下所示
http://localhost:8080/server?1369654461767
互联网速度计算可以使用请求的开始时间、结束时间和可下载文件大小来完成。
但是,我的上述请求的问题是1x1像素,因此无法确定图像大小,并且我不希望单独的服务器调用来计算净速度。
使用客户端的开始时间以及请求和响应中存在的数据来计算互联网速度的任何解决方案。
任何想法都会有帮助。
您将无法计算服务器上的互联网速度。 一个关键问题是启动时间基于客户端时钟,而服务器时钟永远不会足够同步以用于计算速度。
要计算速度,您需要一个完整的往返,您可以从同一台机器(都在客户端上)准确捕获开始和结束时间。 您还需要发送比 1px 图像更重要的内容。 有效负载越小,计算越不准确。
通常速度是通过请求几个已知大小的大响应来计算的。
要使用客户端在查询字符串中提供的时间戳来计算 Node.js 中服务器端的互联网速度,可以使用以下方法:
这是一个示例实现:
var image = document.createElement("img");
image.width = 1;
image.height = 1;
image.src = "http://localhost:8080/server?start=" + new Date().getTime();
const http = require("http");
const server = http.createServer((req, res) => {
// Extract the start time from the query string
const urlParams = new URL(req.url, `http://${req.headers.host}`);
const clientStartTime = parseInt(urlParams.searchParams.get("start"), 10);
// Check if the start time is provided
if (!clientStartTime) {
res.writeHead(400, { "Content-Type": "text/plain" });
return res.end("Missing 'start' query parameter.");
}
// Get the server's current time (response start time)
const serverStartTime = Date.now();
// Create a small response payload (e.g., a 1x1 transparent pixel)
const pixelData = Buffer.from([
0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00,
0x01, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00,
0xff, 0xff, 0xff, 0x21, 0xf9, 0x04, 0x01, 0x00,
0x00, 0x01, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x00,
0x01, 0x00, 0x01, 0x00, 0x00, 0x02, 0x02, 0x44,
0x01, 0x00, 0x3b
]);
// Measure the payload size
const payloadSize = pixelData.length; // in bytes
// Respond with the image
res.writeHead(200, { "Content-Type": "image/gif" });
res.end(pixelData, () => {
// Calculate the total round-trip time
const serverEndTime = Date.now();
const totalTime = serverEndTime - clientStartTime; // in milliseconds
// Calculate internet speed in Mbps
const speedMbps = (payloadSize * 8) / (totalTime / 1000) / 1_000_000;
console.log(`Payload Size: ${payloadSize} bytes`);
console.log(`Total Time: ${totalTime} ms`);
console.log(`Internet Speed: ${speedMbps.toFixed(2)} Mbps`);
});
});
// Start the server
server.listen(8080, () => {
console.log("Server running on http://localhost:8080/");
});
客户端:
?start=<timestamp>
)。服务器端:
start
查询参数用于获取客户端的开始时间。serverEndTime - clientStartTime
)。优点:
限制: