【问题标题】:Creating a private room through a link using node.js使用 node.js 通过链接创建私人房间
【发布时间】:2018-12-18 09:18:15
【问题描述】:

我已经阅读了这个:

https://socket.io/docs/rooms-and-namespaces/#

private chat with socket.io

我想做的是公开聊天:

"/"

还有一个在 /xyz 上的私人聊天,使用此 URL 的每个人都可以在其中交谈。

我稍后会生成随机链接并弄清楚它们,但首先我需要弄清楚如何将公共用户和私人用户连接到不同的套接字?特别是因为他们在做同样的事情,我根本不知道如何有效地做到这一点。

所以首先我必须使用以下方法捕获服务器/私有 URL:

app.get("/private",function(req,res){
res.render("page");
console.log("Rendered private page"); });

我首先想到的解决方案是使用自定义命名空间。

    var namespace = io.of('/private');
namespace.on('connection',function(socket){
    console.log('someone connected to private');
    socket.emit('pmessage',{message:'Connected to a private chat!'});

});

但这成为我的前端的一个问题(我不知道如何操作,因为我对此很陌生)。我基本上会使用重复的代码来处理相同的事情,只是针对不同的用户子集。

所以这个:

    var socket = io.connect('127.0.0.1:8090');

我需要添加一个新的socket,对吧:

    var private = io.connect('127.0.0.1:8090/private');

那么我只是复制所有内容吗?我知道这可能不是正确的解决方案。但我不知道该转向哪里。基本上为 private 而不是 socket 制作一切。

socket.on('message',function(data){
    //Type out the message in the htmlTextField into the htmlChatContent if message was received
    //Keep the other chats
    if(data.message){
        //From w3c:The push() method adds new items to the end of an array, and returns the new length.
        //Example: ["hi","hello"] ---push("wazzzaaap")--->["hi","hello","wazzzaaap"]
        messages.push(data);
        //put messages into the HTML code
        var html = '';
        console.log("Currently in messages" + data.message);
        console.log(data.username);
        for(var i = 0;i<messages.length ;i++){
            //Put it into a string and add a HTML defined symbol sequence for a line break
            //Add username in front of it in bold
            //FIXME: Currently only able to get messages[i] which is just the content
            if(messages[i].username==null){
                html+=messages[i].message + '<br />';
            }
            else{
                html+='<b>'+ messages[i].username + ': </b>' + messages[i].message   + '<br />';

            }

        }
        //Add the message formatted into HTML into the chat content box
        htmlChatContent.innerHTML = html;
        //When sending clear the input field also

        htmlTextField.value = "";
    }
    else{
        //This means there was an error
        //Put error text inside the users text box
        console.log("Error");
        htmlTextField.innerHTML = "There was an sending error!";
    }   
});

我很感激有关如何处理随机生成的链接的指导,我的想法是:

创建链接的数据库,在最后一个人离开的第二个删除条目。但是,我如何对动态链接进行编程?我不能硬编码 500 个不同的选项,对吧?

我是否需要添加更多代码才能使问题变得更好?

【问题讨论】:

  • 您不是在寻找命名空间,而是在寻找房间。一个套接字可以连接任意数量的房间。
  • 但是房间是命名空间的一部分,对吧?如何创建命名空间以使用房间?
  • 不,你不需要命名空间。如果您想在一台服务器上提供不同的服务,则需要它们,例如 /chat/news

标签: javascript node.js


【解决方案1】:

我稍后会生成随机链接并弄清楚它们,但首先我需要弄清楚如何将公共用户和私人用户连接到不同的套接字?

不,您需要 一个 客户端和服务器之间的套接字。然后,您可以将数据从您的服务器发送到一些 aocket。 Socket.io 有相应的空间,这基本上意味着您可以分组管理套接字,并且可以轻松地将数据发送到该组中的套接字。

我不能硬编码 500 个不同的 [套接字/链接],对吗?

不,那太矫枉过正了。只需让客户端/服务器生成随机 url。为了使它们独一无二,您只需获取时间戳并添加一个随机数:

 const id = "" + Math.floor(Math.random() * 1000) + Date.now();

现在,如果您想在 http 服务器上管理/验证客户端,您可以使用动态 url,例如:

 yourserver/private/1272271737

使用快递很容易抓住它们:

 app.get("/private/:id", (req, res) => {
    const { id } = req params;
    // Verify the id and return the clientside code
 });

但实际上只有套接字服务器需要知道房间 ID,所以你可以使用所谓的“hashbang url”,它们看起来像:

 yourserver/private#127272

在服务器端,如果客户端访问/private,您就可以返回应用程序:

 app.get("/private", (req, res) => /*...*/);

但在客户端,您可以将 id 获取为:

 const id = location.hash;

现在客户可以加入相关房间了:

socket.join(id);

现在发送消息时只需发送房间 ID:

 socket.emit("msg", id, "Hi!");

在服务器上,你只需将它广播到那个房间:

io.on('connection', (socket) => {
  socket.on("msg", (id, msg) => {
    io.to(id).emit("msg", msg);
  });
});

【讨论】:

  • 惊人的答案。谢谢。
猜你喜欢
  • 2015-02-23
  • 2021-07-07
  • 2013-10-10
  • 2018-03-10
  • 2017-07-30
  • 2011-11-18
  • 1970-01-01
  • 2020-01-10
  • 1970-01-01
相关资源
最近更新 更多