Advice on implementing “presence” for a web site?

后端 未结 2 1176
被撕碎了的回忆
被撕碎了的回忆 2021-01-14 07:19

Ideally, I\'d like to find simple, lightweight code that allows all the web clients connected to my site to maintain real-time status of who else is currently online.

<
2条回答
  •  一整个雨季
    2021-01-14 07:38

    For real time status, use socket.io. Every time someone connects add them to the connected users list. For accurate stats you will need to keep track of user sessions. See http://www.danielbaulig.de/socket-ioexpress/

    var onlineUsers = {};
    var online = 0;
    
    io.sockets.on('connection', function (socket) {
      onlineUsers[socket.handshake.sessionID] = socket.handshake.session;
      online = Object.keys(onlineUsers).length;
      socket.broadcast.emit('online', online);
    
      socket.on('disconnect', function () {
        delete onlineUsers[socket.handshake.sessionID];
        online--;
        socket.broadcast.emit('online', online);
      });
    });
    

提交回复
热议问题