Javascript Node.js设置套接字ID
从Node.js的官方聊天示例开始。Javascript Node.js设置套接字ID,javascript,node.js,socket.io,real-time,Javascript,Node.js,Socket.io,Real Time,从Node.js的官方聊天示例开始。 系统会提示用户通过“注册”(client.html)将其姓名发送到服务器: 服务器将收到该名称。我希望它将名称作为套接字的标识符。因此,当我需要向该用户发送消息时,我会将其发送到具有其姓名的套接字(姓名存储在数据库中以获取信息)。 将在此处进行更改(server.js): 我正在努力使它工作,因为如果我不能识别插座,我就不能走得更远。因此,我们非常感谢您的帮助。 更新:我知道昵称是套接字的一个参数,所以问题更具体:如何让昵称为“Kyle”的套接字发出消息 将
系统会提示用户通过“注册”(client.html)将其姓名发送到服务器: 服务器将收到该名称。我希望它将名称作为套接字的标识符。因此,当我需要向该用户发送消息时,我会将其发送到具有其姓名的套接字(姓名存储在数据库中以获取信息)。
将在此处进行更改(server.js):
我正在努力使它工作,因为如果我不能识别插座,我就不能走得更远。因此,我们非常感谢您的帮助。
更新:我知道昵称是套接字的一个参数,所以问题更具体:如何让昵称为“Kyle”的套接字发出消息 将套接字存储在如下结构中:
var allSockets = {
// A storage object to hold the sockets
sockets: {},
// Adds a socket to the storage object so it can be located by name
addSocket: function(socket, name) {
this.sockets[name] = socket;
},
// Removes a socket from the storage object based on its name
removeSocket: function(name) {
if (this.sockets[name] !== undefined) {
this.sockets[name] = null;
delete this.sockets[name];
}
},
// Returns a socket from the storage object based on its name
// Throws an exception if the name is not valid
getSocketByName: function(name) {
if (this.sockets[name] !== undefined) {
return this.sockets[name];
} else {
throw new Error("A socket with the name '"+name+"' does not exist");
}
}
};
谢谢你,戴夫,不过你能不能简单一点。我对Node.js还是个新手,这很简单,基本上在模块的作用域中有一个全局对象,用于存储套接字。假设您得到一个套接字,它的昵称为
bob
,当它连接时,您可以通过调用allSockets.addSocket(socket,'bob')来存储它代码>-然后当您想要检索它时,您可以执行socket=allSockets.getSocketByName('bob')代码>,当他断开连接时,你用allSockets.removeSocket('bob')删除它代码>太好了。如何将消息发送到此套接字:io.sockets.emit()
?@mario Yeh与此完全相同,或者干脆allSockets.getSocketByName('bob').emit(msg)
注意,如果名为bob
的套接字不存在,上面的代码会发出一个异常-因此您可以尝试{allSockets.getSocketByName('bob').emit(msg);}catch(e){/*handleerror here*/console.log(e.message);}
socket.on('register', function (name) {
socket.set('nickname', name, function () {
// this kind of emit will send to all! :D
io.sockets.emit('chat', {
msg : "naay nag apil2! si " + name + '!',
msgr : "mr. server"
});
});
});
var allSockets = {
// A storage object to hold the sockets
sockets: {},
// Adds a socket to the storage object so it can be located by name
addSocket: function(socket, name) {
this.sockets[name] = socket;
},
// Removes a socket from the storage object based on its name
removeSocket: function(name) {
if (this.sockets[name] !== undefined) {
this.sockets[name] = null;
delete this.sockets[name];
}
},
// Returns a socket from the storage object based on its name
// Throws an exception if the name is not valid
getSocketByName: function(name) {
if (this.sockets[name] !== undefined) {
return this.sockets[name];
} else {
throw new Error("A socket with the name '"+name+"' does not exist");
}
}
};