简体   繁体   English

使用node.js通过链接创建私人房间

[英]Creating a private room through a link using node.js

I've read through this: 我已经读完了:

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

private chat with socket.io 与socket.io私人聊天

What I'm trying to do is have a public chat on: 我正在尝试进行以下公共聊天:

"/" “/”

And a private chat on /xyz, where everyone that's using this URL can talk in. 在/ xyz上进行私人聊天,使用此URL的每个人都可以进行交谈。

I'll get to generating random links and figuring them out later, but first I need to figure out how to connect public users and private users to different sockets? 我将生成随机链接并在以后解决它们,但是首先我需要弄清楚如何将公共用户和私有用户连接到不同的套接字? Especially since they're doing the same thing I have no idea how to do this efficiently at all. 特别是因为他们在做同一件事,所以我根本不知道如何有效地做到这一点。

So firstly I have to catch a server/private URL using: 因此,首先我必须使用以下命令捕获服务器/专用URL:

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

The solution I've thought of first is using a custom namespace. 我首先想到的解决方案是使用自定义名称空间。

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

});

But this becomes an issue with my frontend(which I know not how to manipulate since I'm very new to this). 但这对我的前端来说是个问题(因为我对此很陌生,所以我不知道该如何操作)。 I'd basically be using duplicate code to handle the same thing, just with different subset of users. 我基本上是使用重复的代码来处理同一件事,只是针对不同的用户子集。

So this: 所以这:

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

I need to add a new socket, right: 我需要添加一个新的套接字,对:

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

Then do I just duplicate everything? 那我只是复制所有内容吗? I know this is probably not the right solution. 我知道这可能不是正确的解决方案。 But I don't know where to turn to. 但我不知道该去哪里。 Basically making everything for private instead of 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!";
    }   
});

I'd appreciate guidance on how to handle randomly generated links, what I've thought of is: 我希望能得到有关如何处理随机生成的链接的指导,我想到的是:

Database of created links, that removes entries the second the last person leaves. 创建的链接数据库,删除最后一个人离开的第二个条目。 However how do I program dynamic links? 但是,如何编程动态链接? I can't hardcode 500 different options, right? 我无法对500个不同的选项进行硬编码,对吗?

Do I need to add more code for the question to be better? 我需要添加更多代码以使问题变得更好吗?

I'll get to generating random links and figuring them out later, but first I need to figure out how to connect public users and private users to different sockets? 我将生成随机链接并在以后解决它们,但是首先我需要弄清楚如何将公共用户和私有用户连接到不同的套接字?

No, you need one socket between the client and your server. 不,您需要在客户端和服务器之间建立一个套接字。 You can then send data to just some of the aockets from your server. 然后,您可以将数据仅从服务器发送到某些aockets。 Socket.io got rooms for that, which basically just means that you can manage the sockets in groups and you send data to the sockets in that group easily. Socket.io有足够的空间,这基本上意味着您可以按组管理套接字,并且可以轻松地将数据发送到该组中的套接字。

I can't hardcode 500 different [sockets / links], right? 我无法硬编码500个不同的[套接字/链接],对吗?

No, that would be overkill. 不,那太过分了。 Just let the client / server generate random urls. 只需让客户端/服务器生成随机网址即可。 To make them unique you could just take the timestamp and add a random number: 要使它们唯一,您只需加上时间戳并添加一个随机数:

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

Now if you want to manage/verify clients on the http server, you could just work with dynamic urls, like: 现在,如果您要在http服务器上管理/验证客户端,则可以使用动态url,例如:

 yourserver/private/1272271737

With express thats quite easy to catch them all: 使用快速多数民众赞成很容易抓住他们所有:

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

But actually only the socket server needs to know the rooms id, so you could use so called "hashbang urls", they look like: 但是实际上只有套接字服务器需要知道房间ID,因此您可以使用所谓的“ hashbang url”,它们看起来像:

 yourserver/private#127272

On the serverside it looks like if the client visits /private so you can just return the application: 在服务器端,看起来客户端是否访问了/private因此您只需返回应用程序即可:

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

But on the clientside you can get the id as: 但是在客户端,您可以通过以下方式获取ID:

 const id = location.hash;

Now the client can join the related room: 现在,客户可以加入相关的会议室:

socket.join(id);

Now when sending a message just send the room id with it: 现在,在发送消息时,只需发送房间ID:

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

On the server, you just broadcast it to that room: 在服务器上,您只是将其广播到该房间:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM