从Node.js的官方聊天示例开始 系统会提示用户通过注册'向服务器发出他的名字。 (client.html):
while (name == '') {
name = prompt("What's your name?","");
}
socket.emit('register', name );
服务器接收名称。我希望它将名称作为套接字的标识符。因此,当我需要向该用户发送消息时,我将其发送到具有其姓名的套接字(名称存储在数据库中以获取信息)。
将在此处进行更改(server.js):
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"
});
});
});
我努力使这项工作变得有效,因为如果我无法识别套接字,我就无法更进一步。所以任何帮助都会非常感激 更新:我知道昵称是套接字的参数,所以更具体的问题是:如何获得具有" Kyle"的套接字。作为发出消息的昵称?
答案 0 :(得分:2)
将套接字存储在如下结构中:
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");
}
}
};