Skip to content
Advertisement

Which is the prefered way to add function to sockets in socket.io?

Is there a “prototype” of all sockets connected to socket.io?

I want to define some functions that will be available for each connected socket.

Currently i have:

io.sockets.on('connection', function(socket) {
  //Define properties and functions for socket
  socket.hello = function(){
    console.log("hello from "+socket.id);
  }

  socket.hello();
});

But i’m defining a ‘new’ hello function for each socket. Is there a socket prototype? so i can have something like:

Socket.prototype.hello = function(){
  console.log("hello from "+socket.id);
}

io.sockets.on('connection', function(socket) {
  socket.hello();
});

Advertisement

Answer

There is, though it doesn’t appear to be available through the main require('socket.io').

Currently, you’ll have to require() socket.js directly to reference it:

var Socket = require('socket.io/lib/socket');

Socket.prototype.hello = function () {
    console.log("hello from " + this.id);
};

Note: From the prototype, you’ll have to reference the instance as this. A socket variable won’t already be available.

Also, like the recommendations against modifying native types, like Object‘s prototype — there’s only one Socket.prototype, so it’s possible to run into collisions of multiple modules trying to define the same method.

Advertisement