我如何在私人聊天中使用node.js和socket.io向共享了session_id的所有用户发送消息?
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);
您必须与创建一个房间conversation_id并让用户订阅该房间,以便您可以向该房间发送私人消息,
conversation_id
客户
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.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 }); });
以下是创建会议室,订阅会议室并将消息发送到会议室的文档和示例: