user3597741
user3597741

Reputation: 449

NodeJs Socket.io Rooms

This is a pretty simple question but i want to make sure that i am scaling our socket.io implementation correctly. We are using socket.io to respond back to the client after a lengthy process on the nodejs backend. So basically client makes call, then socket.io signals the client that the process has completed. Also socket.io ONLY responds to a temporary room that was established for the request.

In nodejs i created a global variable for the following so that i could emit back to the client room:

global.io = require('socket.io')(server);

But to create the room itself I am a little unsure how to create it globally such that only the socket that connected and made the request receives the response.

So if i have 500 client machines that initiate a connection through socket.io, each one will have its own socket. To ensure that the rooms are unique i use a guid across all 500. Of course i do not want all sockets to receive traffic if only one socket for a specific room is supposed to be evaluating the emit....

any ideas?

Upvotes: 0

Views: 182

Answers (2)

Dhaval Italiya
Dhaval Italiya

Reputation: 449

const app = express();
var http = require("http");
var server=http.createServer(app).listen(2525, (req, res) => {
console.log("Server running on", 2525);
});
var socketIO = require("socket.io");
var io = socketIO(server);
global.io = io
io.on("connection", async (socket) => {
   socket.on("joinrooms", async (data) => {
   socket.join(data.userId);
  });

   socket.on("sendMessage", async (data) => {
   console.log("message", data);
   io.to(data.touserId).emit("sendMessage", data);
  });
});

/* Must Read section
Joinrrom data sample
data={
  userId:123 //User's unique id.
}

sendMessage data sample
data={
  userId:123, //sender User's unique id.
  touserId:456, //reciver User's unique id.
}
Here I'm creating a room from the user's unique id(stored in DB) so whenever I 
want to send data to a particular user I will emit an 
event("io.to(data.touserId).emit") using the user's 
a unique id that way only specific users will get messages.
*/

Upvotes: 0

Mavi Domates
Mavi Domates

Reputation: 4521

If I understood your question correctly, you're looking to send information to that 1 socket?

Perhaps something like this:

socket.broadcast.to(socketId).emit('someeventname', eventData);

If you have the connection open with that client, that means you have their socket id through socket.id . You can emit events to just that socket.

Upvotes: 0

Related Questions