Advice on implementing “presence” for a web site?

我的未来我决定 提交于 2019-12-01 11:09:45

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);
  });
});

For anyone reading this in the future. I started with the answer written by fent, but I needed some modifications since things have changed in the intervening 6 years since his answer was published.

I used a Map rather than an Object for storing the session information. this means that the sessionID is no longer required.

const onlineUsers = new Map();

io.on('connection', function (socket) {
    console.log('connection initiated');

    socket.on('userInfo', userInfo => {
        console.log('userInfo', userInfo);

        onlineUsers.set(socket, userInfo);

        io.emit('onlineUsers', Array.from(onlineUsers.values()));
    });

    socket.on('disconnect', function () {
        console.log(onlineUsers.get(socket));

        onlineUsers.delete(socket);

        io.emit('onlineUsers', Array.from(onlineUsers.values()));
    });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!