【问题标题】:Node.js Set socket IDNode.js 设置套接字 ID
【发布时间】:2012-08-18 10:45:23
【问题描述】:

从 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”作为给它发送消息的昵称?

【问题讨论】:

    标签: javascript node.js socket.io real-time


    【解决方案1】:

    将您的套接字存储在这样的结构中:

    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');,当他断开连接时你用@987654325 删除它@
    • 太棒了。如何向此套接字发送消息:io.sockets.emit()?
    • @mario Yeh 完全一样,或者干脆allSockets.getSocketByName('bob').emit(msg);
    • 请注意,如果名称为 bob 的套接字不存在,则上面的代码会发出异常 - 所以你可以这样做 try { allSockets.getSocketByName('bob').emit(msg); } catch (e) { /* handle error here */ console.log(e.message); }
    猜你喜欢
    • 2014-01-30
    • 1970-01-01
    • 2013-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-21
    相关资源
    最近更新 更多