1

从 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”作为昵称的套接字以向其发出消息?

4

1 回答 1

3

Store your sockets in a structure like this:

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");
    }
  }

};
于 2012-08-18T10:55:39.200 回答