【问题标题】:Socket.io live uptime of NodeJS Application?NodeJS应用程序的Socket.io实时正常运行时间?
【发布时间】:2021-04-18 12:12:18
【问题描述】:

我有一个运行网站的 Node.JS express 服务器,我想在前端为用户添加网站的实时正常运行时间。目前,当用户请求页面时,我正在将数据传递给网站。我想直播正常运行时间(在页面上实时更新)我尝试使用带有此代码的 socket.io 来做到这一点。

io.sockets.on('connection', function(sockets){
  var uptime = process.uptime();
  const date = new Date(uptime*1000);
  const days = date.getUTCDate() - 1,
        hours = date.getUTCHours(),
        minutes = date.getUTCMinutes(),
        seconds = date.getUTCSeconds(),
        milliseconds = date.getUTCMilliseconds();
  let segments = [];
  if (days > 0) segments.push(days + ' day' + ((days == 1) ? '' : 's'));
  if (hours > 0) segments.push(hours + ' hour' + ((hours == 1) ? '' : 's'));
  if (minutes > 0) segments.push(minutes + ' minute' + ((minutes == 1) ? '' : 's'));
  if (seconds > 0) segments.push(seconds + ' second' + ((seconds == 1) ? '' : 's'));
  const dateString = segments.join(', ');

  io.sockets.emit('count', {count:dateString})
})

它似乎工作了 2 秒(更新两次),然后没有更多的数据发送到前端。关于如何将process.uptime(); 发送到前端的任何想法? 干杯

编辑: 我需要添加 setInterval(function() 并从 const 更新 dateString 这是服务器更新的代码,

io.sockets.on('connection', function(sockets){
  setInterval(function(){ 
    var uptime = process.uptime();
    const date = new Date(uptime*1000);
    const days = date.getUTCDate() - 1,
      hours = date.getUTCHours(),
      minutes = date.getUTCMinutes(),
      seconds = date.getUTCSeconds();
    let segments = [];

    if (days > 0) segments.push(days + ' day' + ((days == 1) ? '' : 's'));
    if (hours > 0) segments.push(hours + ' hour' + ((hours == 1) ? '' : 's'));
    if (minutes > 0) segments.push(minutes + ' minute' + ((minutes == 1) ? '' : 's'));
    if (seconds > 0) segments.push(seconds + ' second' + ((seconds == 1) ? '' : 's'));
    dateString = segments.join(', ');
    
    sockets.emit('count',{count:dateString}); }, 1000);
})

和客户端代码

    <script>
      var socket = io();
      socket.on('count', function(data){
        $('#count').html(data.count);
      });
    </script>

结果:

【问题讨论】:

    标签: node.js socket.io


    【解决方案1】:

    您似乎只在客户端连接时才向连接的客户端发出正常运行时间。 每次客户端连接时,都会运行 'connection' 事件下的函数。

    如果您希望它自动运行(比如说,每秒),您可以设置一个间隔以每秒发出正常运行时间状态。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-25
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    • 2011-05-18
    • 1970-01-01
    • 2010-12-19
    相关资源
    最近更新 更多