提问者:小点点

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


如何在使用node. js和共享conversation_id的私聊中向所有用户发出消息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);

共2个答案

匿名用户

您必须使用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
    });
});

以下是创建房间、订阅房间和向房间发送消息的文档和示例:

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

匿名用户

当然:简单地说,

这就是你需要的:

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

每当用户加入服务器时,将生成包括ID在内的套接字详细信息。这是真正有助于向特定人员发送消息的ID。

首先我们需要将所有socket. id存储在数组中,

   var people={};

   people[name] =  socket.id;

这里name是收件人名称。示例:

  people["ccccc"]=2387423cjhgfwerwer23;

所以,现在我们可以在发送消息时使用收件人名称获取该socket.id:

为此,我们需要知道recievername.You需要向服务器发出接收者名称。

最后一件事是:

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

希望这对你有用祝你好运