【问题标题】:How to track time between incoming messages from socket server?如何跟踪来自套接字服务器的传入消息之间的时间?
【发布时间】:2019-11-05 16:31:26
【问题描述】:

我创建了一个 websocket (wss) 客户端来监听来自套接字服务器的消息。消息从登录控制台客户端的服务器连续发送。我想测量这些消息之间的时间(我知道它们每 5 秒发生一次,但我需要计算时间,因为不能保证 5 秒)。

我曾考虑通过 Date.now() 存储上一条消息的时间,然后查找最新消息的时间来计算时差,但我不确定如何做到这一点。

socket.onmessage = (event) => {
    if (event.data.substr(4, 9) === 'heartbeat') {
        console.log(event.data.substr(2))  // logs msg to console
        timeHeartbeats(event.data.substr(2), Date.now())
    }
}

// I'm not actually keeping track of the time for 2 messages which is the issue
const timeHeartbeats = (json, mostRecent) => {
    console.log(Date.now() - mostRecent)   // 0 b/c Date.now() is the same as mostRecent (should be ~5000ms if time calc is correct)
}

【问题讨论】:

    标签: javascript time websocket


    【解决方案1】:

    自上次心跳以来的时间:

        socket.onmessage = (event) => {
          if (event.data.substr(4, 9) === 'heartbeat') {
            console.log(event.data.substr(2))  // logs msg to console
            timeFromNow(event.data.substr(2))
          }
        }
    
        // I'm not actually keeping track of the time for 2 messages which is the issue
        const timeHeartbeats = (mostRecent) => (json) => {
          const now = Date.now();
          console.log((now - mostRecent) + ' since last heartbeat');
          mostRecent = now;
        }
    
        const timeFromNow = timeHeartbeats(Date.now());
    

    【讨论】:

    • 谢谢它的工作!我没有将 onmessage 调用更改为 timeFromNow 的较新版本,这就是为什么我认为没有任何效果。真的很感激!
    猜你喜欢
    • 2014-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多