Update all clients using Socket.io?

前端 未结 4 1816
故里飘歌
故里飘歌 2020-12-02 04:39

Is it possible to force all clients to update using socket.io? I\'ve tried the following, but it doesn\'t seem to update other clients when a new client connects:

S

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-02 05:09

    It's not actually sending an update to the other clients at all, instead it's just emitting to the client that just connected (which is why you see the update when you first load)

    // socket is the *current* socket of the client that just connected
    socket.emit('users_count', clients); 
    

    Instead, you want to emit to all sockets

    io.sockets.emit('users_count', clients);
    

    Alternatively, you can use the broadcast function, which sends a message to everyone except the socket that starts it:

    socket.broadcast.emit('users_count', clients);
    

提交回复
热议问题