Nadjib Mami
Nadjib Mami

Reputation: 5830

Node.js Set socket ID

Starting from the official chat example of Node.js.
The user is prompted to emit his name to the server through 'register' (client.html):

            while (name == '') {
               name = prompt("What's your name?","");
            }                
            socket.emit('register', name );

The server receives the name. I want it to make the name as the identifier of the socket. So when I need to send a message to that user I send it to the socket having his name (Names are stored in a database for the info).
Changes will take place here (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"
         });
      });
   });

I'm struggling making this works, because I can't go any farer if I can't identify the socket. So any help will be really appreciated.
Update: I understand that nickname is a parameter for the socket, so the question is more specifically: how to get the socket that has "Kyle" as a nickname to emit it a message?

Upvotes: 1

Views: 2800

Answers (1)

DaveRandom
DaveRandom

Reputation: 88677

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

};

Upvotes: 3

Related Questions