Asa Carter Asa Carter - 1 year ago 143
Javascript Question

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

How do I emit a message to all users in a private chat sharing a conversation_id using node.js and

var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('').listen(server);
conversations = {};

app.get('/', function(req, res) {

io.sockets.on('connection', function (socket) {

socket.on('send message', function (data) {

var conversation_id = data.conversation_id;

if (conversation_id in conversations) {

console.log (conversation_id + ' is already in the conversations object');

// emit the message [data.message] to all connected users in the conversation

} else {
socket.conversation_id = data;
conversations[socket.conversation_id] = socket;

conversations[conversation_id] = data.conversation_id;

console.log ('adding ' + conversation_id + ' to conversations.');

// emit the message [data.message] to all connected users in the conversation



Answer Source

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,


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


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

socket.on('send message', function(data) {
    console.log('sending room post',;'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. Rooms
  2. Socket.IO subscribe to multiple channels
  3. rooms difference between and
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download