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

后端 未结 6 1044
故里飘歌
故里飘歌 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 08:01

    Overview:

    After socket.io connection has been established, you create a new Date object on the client, let's call it startTime. This is your initial time before making a request to the server. You then emit a ping event from the client. Naming convention is totally up to you. Meanwhile server should be listening for a ping event, and when it receives the ping, it immediately emits a pong event. Client then catches the pong event. At this time you want to create another date object that represents Date.now(). So at this point you have two date objects - initial date before making a request to the server, and another date object after you make a request to the server and it replied. Subtract the startTime from current time and you have the latency.

    Client

    var socket = io.connect('http://localhost');
    var startTime;
    
    setInterval(function() {
      startTime = Date.now();
      socket.emit('ping');
    }, 2000);
    
    socket.on('pong', function() {
      latency = Date.now() - startTime;
      console.log(latency);
    });
    

    Server

    io.sockets.on('connection', function (socket) {
      socket.on('ping', function() {
        socket.emit('pong');
      });
    });
    

    Also available as a Github Gist.

提交回复
热议问题