尝试实施简单的延迟检查,但我不确定我是否做得对。
socket.emit('ping');
在客户端每2秒调用一次,但服务器在下次调用之前从不响应它(见下面的截图)。
在同一屏幕截图中,我们可以看到pong
仅在第一次ping
通话后24秒(12x)收到。它说1094
与最后一次ping
电话有关,但它仍然非常高。
我错过了什么?
client.js
function start(){
//starts connection
socket = io();
//Get socketID
socket.on('socketID', function(data) {
console.log('socketID: ' + socket.id);
});
//Start Measure latency
setInterval(function() {
startTime = Date.now();
console.log('ping: ' + startTime);
socket.emit('ping');
}, 2000);
socket.on('pong', function() {
latency = Date.now() - startTime;
console.log('pong ' + latency);
});
//end latency
}
app.js
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server,{});
server.listen(8081, function(){
console.log("Server is now running...")
});
app.get("/", function(req, res){
//res.send("It works!");
res.sendFile(__dirname + '/client/index.html');
});
app.use(express.static('client'));
//start server logic
//on connect
io.sockets.on('connection', function(socket){
socket.emit('socketID', {id: socket.id});
console.log('New player connected: ' + socket.id);
socket.on('ping', function() {
socket.emit('pong');
});
});
结果: