Socket.io不会更新客户端数据

时间:2017-12-31 17:28:33

标签: node.js socket.io

我在导航栏中有在线计数器,该计数器与online事件相关联。它显示了在线用户的数量,但是当我在另一个窗口中连接时,计数器不会更新(当我关闭窗口时也不会)。刷新后也显示正确的数字。

服务器

let currentConnections = {};
let numberOfConnections = () => Object.keys(currentConnections).length;

io.sockets.on('connection', (socket) => {
    console.log('New user connected.');
    currentConnections[socket.id] = { socket: socket };
    socket.emit('online', { count: numberOfConnections() });

    socket.on('disconnect', () => {
        console.log('User has disconnected.');
        delete currentConnections[socket.id];
        socket.emit('online', { count: numberOfConnections() });
    });
});

客户端

var socket = io.connect('http://localhost:3000');

socket.on('online', function(data) {
    $("#online").html(data.count);
    console.log(data);
});

1 个答案:

答案 0 :(得分:1)

您需要将更新的计数广播到所有连接,而不仅仅是新连接或断开的连接。在这两个地方你都可以改变它:

socket.emit('online', { count: numberOfConnections() });

到此:

// send new count to all connections
io.emit('online', { count: numberOfConnections() });