【发布时间】:2018-12-18 09:18:15
【问题描述】:
我已经阅读了这个:
https://socket.io/docs/rooms-and-namespaces/#
我想做的是公开聊天:
"/"
还有一个在 /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