Monday, April 24, 2017

How to private chat using node.js and socket.io


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 my Stackoverflow answer : http://stackoverflow.com/a/23623724/453486

2 comments:

Unknown said...

Just wanna ask one question? is conversation_id built-in variable or we have to provide it in the emit method. And how it is gonna work? Will user enter the conversation_id given to him to join the chat??

Srikanth Jeeva said...

conversation_id is not a built in variable. Its a random ID that you can generate for this particular conversation.

for example: For this conversaton, we can generate a random ID named "unknown_aug12"

var conversation_id = "chat_with_unknown_aug12"
socket.emit('subscribe', conversation_id);