Skip to content

using socket how to broadcast message to specific users who has role_id = 1

Using Socket and node express i want to send a message to all users who has role_id 1 but whenever i broadcast message all users receive it.

// let suppose this is message
let Message = 'hello all users'
//socket code
socket.emit('message', Message);

//but i want to send message to below users.
// I am not a good programmer and i am new to socket.



//during user login time i return this 
if (login == true) {
  user.status = 'Online';
}

status has nothing with message. its just updating user status

Answer

//first of all join user to room if has role id 1
//during user login time i return this 
let role_room_id = 1;
if (login == true) {
  user.status = 'Online';
  socket.join(role_room_id);
}

///then emit message in that room
socket.broadcast.to(role_room_id).emit('message', Message);