# Socket namespace for a chat module

I finally managed to work with socket.io namespace stuff which I'm using for building a chat module. Here, employees of multiple organizations can join and vhat with other employees of the respective organization. What I'm doing at here is creating separate namespaces for each organization. So, it'll be easier for me to manage all employees of different organizations.

Here is my server side code:

var express = require('express'),
http = require('http'),
app = express(),
server = http.createServer(app),
io = require('socket.io').listen(server);

var nsp_1005 = io.of('/nsp_bucket_1005');
nsp_1005.on('connection', function(socket){
console.log('someone connected to namespace bucket 1005');

});

socket.on('disconnect', function(){
console.log('Someone disconnected from namespace bucket 1005.');
});
});

var nsp_1010 = io.of('/nsp_bucket_1010');
nsp_1010.on('connection', function(socket){
console.log('someone connected to namespace bucket 1010');

});

socket.on('disconnect', function(){
console.log('Someone disconnected from namespace bucket 1010.');
});
});


Those 1005, 1010 codes are Organization IDs. Sorry for the wired naming scheme. But, one thing right now I'm feeling the way I've made this code is not so good. Because I'm duplicating the code at the time of creating namespace for each organization. Can anyone suggest a better way to arrange this code?

Extract the common logic to a function, where the varying parts are parameters. Unless I'm missing something, this looks trivially easy to do:

function setup_namespace(org_id) {
var nsp = io.of('/nsp_bucket_' + org_id);
nsp.on('connection', function(socket){
console.log('someone connected to namespace bucket ' + org_id);

});

socket.on('disconnect', function() {
console.log('Someone disconnected from namespace bucket ' + org_id);
});
});
return nsp;
}

var nsp_1005 = setup_namespace(1005);
var nsp_1010 = setup_namespace(1010);


If you don't need to retain those variables, then you could remove the variables and just leave the calls:

setup_namespace(1005);
setup_namespace(1010);

• Thanks for your quick reply. It's working now. Silly things, but as i'm a new to this socket stuff.. i got confuse. Thanks again for your help. – Suresh Dec 21 '14 at 8:37