使用node.js和socket.io在密钥之间创建私人聊天 [英] Creating a private chat between a key using a node.js and socket.io

查看:241
本文介绍了使用node.js和socket.io在密钥之间创建私人聊天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用node.js和socket.io与私人聊天中的所有用户发送一条消息,分享一个conversation_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);


推荐答案

你必须用<$ c $创建一个房间c> 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:


  1. Socket.io Rooms

  2. Socket.IO订阅多个频道

  3. 在broadcast.to和sockets.in之间的Socket.io房间区别

  1. Socket.io Rooms
  2. Socket.IO subscribe to multiple channels
  3. Socket.io rooms difference between broadcast.to and sockets.in

这篇关于使用node.js和socket.io在密钥之间创建私人聊天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆