0

The code below works fine by broadcasting typing notification and chat messages to all connected users.

Here is what I want: How do I send typing notification and chat messages only to users connected to a particular room say Room1, Room2 etc.

here is the code

index.html

var socket = io(); 
var user = 'nancy';
function submitfunction(){
  var from = 'nancy';
  var message = 'hello Nancy';
  socket.emit('chatMessage', from, message);
}

function notifyTyping() {
  var user = 'nancy' 
  socket.emit('notifyUser', user);
}

socket.on('chatMessage', function(from, msg){
  //sent message goes here
});

socket.on('notifyUser', function(user){
    $('#notifyUser').text(nancy is typing ...');
  setTimeout(function(){ $('#notifyUser').text(''); }, 10000);
});

server.js

var io = require('socket.io')(http);
io.on('connection', function(socket){ 
  socket.on('chatMessage', function(from, msg){
    io.emit('chatMessage', from, msg);
  });


  socket.on('notifyUser', function(user){
    io.emit('notifyUser', user);
  });
});

am using npm installed socket.io ^2.3.0

Nancy Moore
  • 2,322
  • 2
  • 21
  • 38

1 Answers1

0

To send the message to a specific room, you will have to create and join a room with roomId. Below is a basic code snippet

//client side
const socket = io.connect();
socket.emit('create', 'room1');

// server side code
  socket.on('create', function(room1) {
    socket.join(room1);
  });

To emit data to a specific room 

// sending to all clients in 'room1'except sender
  socket.to('room1').emit('event',data);

// sending to all clients in 'room1' room, including sender
 io.in('room1').emit('event', 'data');

You can follow this question for details on how to create a room?

Creating Rooms in Socket.io

This emit cheat sheet might also be useful: https://github.com/socketio/socket.io/blob/master/docs/emit.md

Sandeep Patel
  • 4,815
  • 3
  • 21
  • 37