获取基于Websocket的网络延时
npm下载nodejs-websocket
npm install nodejs-websocket
构建服务器,接收ping请求,并返回pong请求
var ws = require("nodejs-websocket");
console.log("开始建立连接...")
var server = ws.createServer(function(conn){
conn.on("text", function (str) {
if (str.indexOf('ping') !== -1) {
console.log("收到客户端"+str);
setTimeout(() => {
conn.sendText(str.replace(/i/, "o"))
}, Math.random()*470+10);
}
setTimeout(() => {
conn.sendText("我是服务器")
},1000);
})
conn.on("close", function (code, reason) {
console.log("关闭连接")
});
conn.on("error", function (code, reason) {
console.log("异常关闭")
});
}).listen(8001)
console.log("WebSocket建立完毕")
连接成功后发送请求,并记录时间并存入数组
ws.onopen = function (e) {
pingInterval = setInterval(() => {
let now = new Date().getTime();
let timeStampKey = now.toString().substr(3);
if(Object.keys(timemap).length > 10){
timemap = {};
}
console.log(Object.keys(timemap).length);
timemap[timeStampKey] = [now];
ws.send('ping'+ timeStampKey)
}, 1000);
接收服务端返回信息,记录时间,寻找对应位置并存入
console.log(timemap);
if (message.data.indexOf('pong') !== -1) {
var timeStampKey = message.data.slice(4);
let backtime = new Date().getTime();
if (timemap[timeStampKey]) {
timemap[timeStampKey].push(backtime);
}
let netspeed = getAverage(timemap);
document.getElementById('netspeed').innerHTML = netspeed ;
}
求平均值
function getAverage(map) {
let sum = 0;
for (let i in map) {
if (map[i].length === 2)
sum += (map[i][1] - map[i][0])
}
return Math.round(sum / Object.keys(map).length);
}
最终效果
|