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

问题描述 投票:0回答:1

我在导航栏中有在线计数器,它与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);
});
node.js socket.io
1个回答
1
投票

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

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

对此:

// send new count to all connections
io.emit('online', { count: numberOfConnections() });   
© www.soinside.com 2019 - 2024. All rights reserved.