Creating a private chat between a key using a node.js and socket.io

You have to create a room with conversation_id and make users to subscribe to that room, so that you can emit a private message to that room it by,

client

var socket = io.connect('http://ip:port');

socket.emit('subscribe', conversation_id);

socket.emit('send message', {
    room: conversation_id,
    message: "Some message"
});

socket.on('conversation private post', function(data) {
    //display data.message
});

Server

socket.on('subscribe', function(room) {
    console.log('joining room', room);
    socket.join(room);
});

socket.on('send message', function(data) {
    console.log('sending room post', data.room);
    socket.broadcast.to(data.room).emit('conversation private post', {
        message: data.message
    });
});

Here is the docs and example for creating a room, subscribing to the room and Emit message to a room:

  1. Socket.io Rooms
  2. Socket.IO subscribe to multiple channels
  3. Socket.io rooms difference between broadcast.to and sockets.in

Leave a Comment