使用node.js和socket.io创build密钥之间的私人聊天

如何使用node.js和socket.io向共享conversation_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创build一个房间,让用户订阅那个房间,这样你才能发送一个私人信息到那个房间,

客户

 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 }); }); 

以下是创build房间,订阅房间和发送消息给房间的文档和示例:

  1. Socket.io客房
  2. Socket.IO订阅多个通道
  3. Socket.io与broadcast.to和sockets.in的区别

SURE:简单地说,

这是你需要的:

  io.to(socket.id).emit("event", data); 

每当用户join到服务器,套接字细节将生成包括ID。这是ID真的有助于发送消息给特定的人。

首先我们需要存储所有的socket.ids数组,

  var people={}; people[name] = socket.id; 

这里的名字是接收者的名字。 例:

  people["ccccc"]=2387423cjhgfwerwer23; 

所以,现在我们可以在发送消息的时候用接收者的名字来获取这个socket.id:

为此,我们需要知道接收者名称。您需要将接收者名称发送到服务器。

最后的事情是:

  socket.on('chat message', function(data){ io.to(people[data.reciever]).emit('chat message', data.msg); }); 

希望这对你有好处。祝你好运