本文介绍了使用 node.js 和 socket.io 在密钥之间创建私人聊天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用 node.js 和 socket.io 向私人聊天中的所有用户发送消息,共享一个 session_id?
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);
推荐答案
您必须使用 conversation_id
创建一个房间,并让用户订阅该房间,以便您可以向那个房间吧,
You have to 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,
客户
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
});
});
以下是创建房间、订阅房间和向房间发送消息的文档和示例:
Here is the docs and example for creating a room, subscribing to the room and Emit message to a room:
这篇关于使用 node.js 和 socket.io 在密钥之间创建私人聊天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!