How can I find the response time (latency) of a client in NodeJS with sockets (socket.io)?

后端 未结 6 981
故里飘歌
故里飘歌 2021-01-30 07:11

I\'m trying to create a multiplayer game with NodeJS and I want to synchronize the action between clients.

What would be the best way to find the latency (the time that

6条回答
  •  日久生厌
    2021-01-30 07:56

    After reading all these answers...

    ...I still wasn't satisfied. I visited the official docs and well, well, well - the solution is already built-in.

    You just need to implement it - check out mine:

    Client

    // (Connect to socket).
    
    var latency = 0;
    
    socket.on('pong', function(ms) {
        latency = ms;
    
        console.log(latency);
    });
    
    // Do cool things, knowing the latency...
    

     Server

    var server = require('http').Server(app);
    
    // "socket.io": "^1.7.1"
    // Set pingInterval to whatever you want - 'pong' gets emitted for you!
    var io = require('socket.io')(server, {pingInterval: 5000});
    

提交回复
热议问题