Update all clients using Socket.io?

前端 未结 4 1810
故里飘歌
故里飘歌 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:05

    You can follow this example for implementing your scenario.

    You can let all of clients to join a common room for sending some updates. Every socket can join room like this:

    currentSocket.join("client-presence") //can be any name for room
    

    Then you can have clients key in you sockets which contains multiple client's data(id and status) and if one client's status changes you can receive change event on socket like this:

    socket.on('STATUS_CHANGE',emitClientsPresence(io,namespace,currentSocket); //event name should be same on client & server side for catching and emiting
    

    and now you want all other clients to get updated, so you can do something like this:

    emitClientsPresence => (io,namespace,currentSocket) {
      io.of(namespace)
            .to(client-presence)
            .emit('STATUS_CHANGE', { id: "client 1", status: "changed status" });
    }
    

    This will emit STATUS_CHANGE event to all sockets that have joined "client-presence" room and then you can catch same event on client side and update other client's status.

提交回复
热议问题