socket.io-redis-adapter icon indicating copy to clipboard operation
socket.io-redis-adapter copied to clipboard

does it update io.sockets.sockets ?

Open Mohammad-DH opened this issue 3 years ago • 3 comments

sorry this is just a question io.sockets.sockets is the list of all sockets is this adapter update this list ? (" Note: no data is stored in Redis itself ")

Mohammad-DH avatar Sep 20 '22 09:09 Mohammad-DH

Hi! No, io.sockets.sockets contains only the socket instances on the current nodes.

darrachequesne avatar Sep 20 '22 11:09 darrachequesne

so what way is there to get all the socket from all instances ?

Mohammad-DH avatar Sep 21 '22 05:09 Mohammad-DH

To fetch all sockets, you can use the fetchSockets() method:

// return all Socket instances of the main namespace
const sockets = await io.fetchSockets();

// return all Socket instances in the "room1" room of the main namespace
const sockets = await io.in("room1").fetchSockets();

// return all Socket instances in the "room1" room of the "admin" namespace
const sockets = await io.of("/admin").in("room1").fetchSockets();

// this also works with a single socket ID
const sockets = await io.in(theSocketId).fetchSockets();

// then
for (const socket of sockets) {
  console.log(socket.id);
  console.log(socket.handshake);
  console.log(socket.rooms);
  console.log(socket.data);
  socket.emit(/* ... */);
  socket.join(/* ... */);
  socket.leave(/* ... */);
  socket.disconnect(/* ... */);
}

Reference: https://socket.io/docs/v4/server-instance/#fetchsockets

darrachequesne avatar Sep 21 '22 08:09 darrachequesne

@darrachequesne Hello, how to update socket.data on the other instances? is any API?

shenX-2021 avatar Oct 08 '22 03:10 shenX-2021

@shenX-2021 you can use the serverSideEmit() method, to send an event to the other servers:

io.serverSideEmit("hello");

io.on("hello", () => {
  // do something
});

Reference: https://socket.io/docs/v4/server-instance/#serversideemit

darrachequesne avatar Oct 08 '22 08:10 darrachequesne

I think this can now be closed, please reopen if needed.

darrachequesne avatar Oct 08 '22 08:10 darrachequesne