I'm using Node.JS with Socket.IO and Express. My goal is to create a module that creates a custom Socket.IO+Express server, loaded with all the functions that my application needs. For example, keeping track of the number of clients connected at any given time.
The catch is, I'd like to have the server work as a class, if possible. I've seen other Node.JS modules use classes just fine (including Socket.IO itself) so I assume it shouldn't conflict with Node's module-oriented architecture. The reason why I need it to work with classes is that I want to be able to create multiple instances of the server with ease.
Here's what I have (simplified for brevity):
index.js
var myserver = require("./myserver");
var myserver1 = myserver.createServer();
var myserver2 = myserver.createServer();
myserver1.port = 8080;
myserver2.port = 8081;
myserver1.start();
myserver2.start();
myserver.js
var io = require("socket.io");
var express = require("express");
var path = require("path");
function MyServer()
{
this.port = 8080;
this.expressServer = null;
this.ioServer = null;
this.clientCount = 0;
}
Server.prototype.getClientCount = function()
{
return this.clientCount;
}
Server.prototype.start = function()
{
this.expressServer = express.createServer();
this.ioServer = io.listen(this.expressServer);
this.expressServer.listen(this.port);
this.ioServer.sockets.on(
"connection",
function()
{
this.clientCount++;
console.log(this.clientCount + " clients connected.");
}
);
}
exports.createServer = function() { return new MyServer(); };
The code inside the "connection"
callback is incorrect, because the this
keyword in Socket.IO's callback refers to the client object that triggered the "connection"
event, not to the MyServer
object. So is there a way to access the clientCount
property from inside the callback?
Create a proper closure by copying this
into another a variable (most people like to call it self
but some prefer that
) and using it in your connection handler:
var self=this;
this.ioServer.sockets.on(
"connection",
function()
{
self.clientCount++;
console.log(self.clientCount + " clients connected.");
}
);