问题

如何使用node.js和socket.io在共享对话_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 的房间,并让用户订阅该房间,以便您可以通过这个房间发出一个私有的消息,

客户

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

以下是创建房间,订阅房间和Emit消息到房间的文档和示例:

  1. Socket.io Rooms
  2. Socket.IO订阅多个通道
  3. Socket.io 室之间的bloadcast.to和sockets.in

  相同标签的其他问题

javascriptnode.jssocket.iochat