node.js - 如何生成房间 ID 并强制两个用户加入该房间?

标签 node.js mongodb express socket.io

我正在使用 node.js、socket.io 和 mongoose 构建一个聊天应用程序。我的目标是建立一对一的聊天,它类似于 facebook 网络聊天。所以基本上每当我点击一个用户时,它都会转到该用户 url 并可能与他/她聊天

但我面临的问题是我只能将消息发送给目标用户,而不能发送给我自己。

这是当前代码

服务器端

socket.on('chatTo', function(data){
      User.findOne({ username: data.destinationUsername, socketId: { '$ne': null}}, function(err, foundUser) {
        if (foundUser) {
          io.to(foundUser.socketId).emit('incomingChat', { sender: user.username, message: data.message });

        } else {
          io.to(socket.id).emit('deliverError', { error: foundUser + ' is not online' });

        }
      });
    });

客户端

$(function() {

  var socket = io();


  function chatTo(message, destinationUsername) {
    socket.emit('chatTo', { message: message, destinationUsername });
  }


  $('#sendMessage').submit(function(){
    var input = $('#message').val();
    var username = $('#username').val();
    chatTo(input, username);
    $('#message').val('');
    return false;
  });


  socket.on('incomingChat', function(data) {
    var html = data; // Messages to append to media-list

    $('.media-list').append(html);
  });
});

所以这里发生的事情是,在客户端,用户 A 单击表单提交以提交消息,它将调用 chatTo 函数并发出数据。只是想让你们知道,inputusername 来自html 页面。它看起来像这样

input = "Hello";

username = "jackmoscovi" // user's username

然后它会将这两个数据发送回服务器,socket.on('chatTo') 正在监听。在一些 MongoDB 操作之后,如果找到用户然后发送到那个特定的套接字。

结果会是

enter image description here

bat 侠发出的信息只出现在 clown 的页面上,但不会出现在 bat 侠的页面上。我知道这一点,因为我专门向那个套接字发出信号。真正的问题是如何强制这两个用户在一个独特的房间里?我应该创建一个新的 Room mongoose 模型吗?然后调用 socket.join('uniqueRoom')?

然后简单地 io.to('uniqueRoom').emit("Message?");

我将如何实现这种房间机制?

我已经苦苦挣扎了 2 天,请有人结束这种痛苦:(

最佳答案

首先像这样创建一个 Mongoose 模式

var mongoose = require('mongoose'),
    Schema = mongoose.Schema;
var messageSchema=new Schema({
    sender : {
        type : String,
    },
    receiver : {
        type : String.
    },
    message : {
        type : String
    }
})
mongoose.model('messages',messageSchema);

然后在服务器代码中

message = mongoose.model('messages')
socket.on('chatTo', function(data){  // data is json containing sender, receiver and message
    User.findOne({ username: data.destinationUsername, socketId: { '$ne': null}}, function(err, foundUser) {
        if (foundUser) {
            io.to(foundUser.socketId).emit('incomingChat', { sender: user.username, message: data.message });
            socket.emit('incomingChat', { sender: user.username, message: data.message });
            var newMessage = new message({
                sender : data.sender,
                receiver : data.receiver,
                message : data.message
            })
            newMessage.save(function (err, data){
                if(err)
                    console.log(err)
            })
        } else {
            io.to(socket.id).emit('deliverError', { error: foundUser + ' is not online' });

        }
    });
});

关于node.js - 如何生成房间 ID 并强制两个用户加入该房间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35088179/

相关文章:

node.js - 使用 Google Cloud Storage + Node.js 创建存储桶

node.js - 如何从外部js访问Object值

node.js - 使用 mongoose 计算嵌套数组

mongodb - 将集合聚合并插入到mongodb中的不同集合中

javascript - Mongoose:如何使用回调中的变量更新文档?

node.js - 具有大图像尺寸的 Base64 图像上的 Nodejs CORS 错误

node.js - Nodejs - 异步/等待我的 Controller

javascript - 为什么传递的方法/函数中的 `this` 与传递的对象上的方法调用不同

javascript - Express/Mongoose 项目中的 HTTP Get 和 Post 请求中缺少内容

node.js - 仅返回数据库中数组中的一个对象