How do I emit a message to all users in a private chat sharing a conversation_id using node.js and socket.io?
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
conversations = {};
app.get('/', function(req, res) {
res.sendfile('/');
});
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
}
})
});
server.listen(8080);
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…