如何使用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);
Srikanth Jee.. 55
您必须创建一个房间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 }); });
以下是创建房间,订阅房间和向房间发送消息的文档和示例:
Socket.io客房
Socket.IO订阅多个频道
Socket.io在broadcast.to和sockets.in之间的区别
太好了,谢谢,它完美无缺.我将`socket.broadcast.to()`更改为`io.sockets.in()`,以便它包含发送套接字. (2认同)
Trojan.. 15
当然:简单地说,
这就是你需要的:
io.to(socket.id).emit("event", data);
每当用户加入服务器时,将生成包括ID的套接字详细信息.这是真正有助于向特定人员发送消息的ID.
首先我们需要将所有socket.id存储在数组中,
var people={}; people[name] = socket.id;
这里的名字是收件人姓名.例:
people["ccccc"]=2387423cjhgfwerwer23;
所以,现在我们可以在发送消息时使用接收者名称获取socket.id:
为此我们需要知道recievername.You需要向服务器发出接收者名称.
最后一件事是:
socket.on('chat message', function(data){ io.to(people[data.reciever]).emit('chat message', data.msg); });
希望这对你有用.!!祝你好运