Getting Negative Time Duration in Sender-to-Client Application using Date.now() api

23 Views Asked by At

I'm encountering an issue with time duration calculation in my sender-to-client application built using JavaScript Date API. The application involves sending data from a sender to a client via a server. However, I'm noticing that sometimes the calculated time duration between sending and receiving the data becomes negative.

Issue Details:

Scenario: The sender sends data to the server, which then forwards it to the client. I'm measuring the time taken between sending the data from the sender and receiving it at the client end using Date.now() API.

Problem: Occasionally, the time duration calculated turns out to be negative. This doesn't seem to align with the expected behavior, as time duration should always be positive.

server code

const WebSocket = require("ws");

// Create a WebSocket server instance
const wss = new WebSocket.Server({ port: 9090 });

// Array to store all connected clients
const clients = [];

// Event handler for WebSocket connections
wss.on("connection", function connection(ws) {
  // Push the new connection to the clients array
  clients.push(ws);

  // Event handler for incoming messages from clients
  ws.on("message", function incoming(message) {
    ws.send(message.toString());
    // Broadcast the received message to all connected clients
    clients.forEach(function each(client) {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(message.toString());
      }
    });
  });

  // Event handler for closing the connection
  ws.on("close", function close() {
    // Remove the disconnected client from the clients array
    const index = clients.indexOf(ws);
    if (index > -1) {
      clients.splice(index, 1);
    }
  });
});

Sender application code

const MSG_INTERVAL = 50;


function startApp() {
    const websocketUrl = "ws://localhost:9090";
    const socket = new WebSocket(websocketUrl);

    // Handle connection open event
    socket.onopen = function (event) {
        console.log("Connection established!");
    };

    const timerId = setInterval(() => {
    const sendtimestamp = new Date();
    const dateTimeStamp = sendtimestamp.toISOString();

        // Create an object with the message
        const messageObject = {
            publishTime: dateTimeStamp
    };
        socket.send(JSON.stringify(messageObject));
  }, MSG_INTERVAL);

    // Handle connection close event
    socket.onclose = function (event) {
        console.log("Connection closed.");
    };
}


// Handle on load app
window.onload = startApp;

Reciver appilcation

function startApp() {
    const websocketUrl = "ws://localhost:9090";
    const socket = new WebSocket(websocketUrl);

    // Handle connection open event
    socket.onopen = function (event) {
        console.log("Connection established!");
    };

    // Handle incoming messages from the server
    socket.onmessage = function (event) {
        // const recievedTime = performance.now();
        const recievedTimeNow = new Date();
        const jsonData = JSON.parse(event.data);

        const publishTimeMillis = new Date(jsonData.publishTime).getTime(); // Convert publishTime to milliseconds
        const timeDifference = recievedTimeNow - publishTimeMillis ; // Calculate absolute difference in milliseconds
        console.log(`publish_to_subscribe_time: ${timeDifference}, publishTime: ${jsonData.publishTime}, receiveTime: ${recievedTimeNow.toISOString()}`);
                if (timeDifference < 0) {
            alert("Time diffference is negative");
            }

    };

    // Handle connection close event
    socket.onclose = function (event) {
        console.log("Connection closed.");
    };
}

// Handle on load app
window.onload = startApp;

Receiver console log

publish_to_subscribe_time: 0, publishTime: 2024-03-27T16:01:58.412Z, receiveTime: 2024-03-27T16:01:58.412Z
publish_to_subscribe_time: 14, publishTime: 2024-03-27T16:01:59.419Z, receiveTime: 2024-03-27T16:01:59.433Z
publish_to_subscribe_time: 0, publishTime: 2024-03-27T16:02:00.416Z, receiveTime: 2024-03-27T16:02:00.416Z
publish_to_subscribe_time: 0, publishTime: 2024-03-27T16:02:01.423Z, receiveTime: 2024-03-27T16:02:01.423Z
publish_to_subscribe_time: -1, publishTime: 2024-03-27T16:02:09.412Z, receiveTime: 2024-03-27T16:02:09.411Z

I expect the time duration between sending and receiving the data to always be positive, indicating the time taken for the data transmission. The sender, receiver and server running on same machine. Issue also getting using Performance.now() API. I also checked with different browsers and OS.

What could be causing the negative time duration in this scenario? Why the browser not getting correct system time in different tabs? How can I ensure that the time duration is always positive and accurately reflects the time taken for data transmission?

0

There are 0 best solutions below