In my socket io server, currently whenever a user connects I add them to an array and join them to a room with the name being their unique user Id. The code for this is shown below:
Server.js:
var users = []
io.on('connect', (socket) => {
socket.on('join', (data) => {
// Add user to array
users.push({socketId: socket.id, username: data.username, userId: data.uid})
// Join a user into their own room with the name being their unique user Id
socket.join(data.uid)
})
})
When sending to one specific user, currently I am doing the following:
// Find the user from the users array
const user = users.find(u => u.userId = userId)
// Emit to room that I joined them to after connecting
io.to(user.userId).emit("send message", messageData)
An alternative approach would be to not have users join rooms with their own user id’s after connecting, and instead directly send events to users socket Ids. This would look like the following:
io.to(user.socketId).emit("sendMessage", messageData)
Using this method, users would not need to join their own room as soon as they connect, unlike the first method.
Is there any benefit to using this second approach as opposed to the first? Is there any scenarios where one solution would fit better?
Also, instead of joining a user to their own room on connect, could I just use io.to(user.socketId).emit("send message", data) which uses the user’s socket id as the room name, as I believe socket IO always automatically connects a user to their own room using their socket Id. However, this feature is mentioned in v3 of socket io documentation and not v4, therefore is this still a built in feature? Thanks.
