how to organize socket handling in node.js and socket.io app
node.js, socket.io, sockets, websocket
Solution
To organize your event handlers in different files, you could use a structure like this:
./main.js
var io = require('socket.io');
var Chat = require('./EventHandlers/Chat');
var User = require('./EventHandlers/User');
var app = {
allSockets: []
};
io.sockets.on('connection', function (socket) {
// Create event handlers for this socket
var eventHandlers = {
chat: new Chat(app, socket),
user: new User(app, socket)
};
// Bind events to handlers
for (var category in eventHandlers) {
var handler = eventHandlers[category].handler;
for (var event in handler) {
socket.on(event, handler[event]);
}
}
// Keep track of the socket
app.allSockets.push(socket);
});
./EventHandlers/Chat.js
var Chat = function (app, socket) {
this.app = app;
this.socket = socket;
// Expose handler methods for events
this.handler = {
message: message.bind(this) // use the bind function to access this.app
ping: ping.bind(this) // and this.socket in events
};
}
// Events
function message(text) {
// Broadcast message to all sockets
this.app.allSockets.emit('message', text);
});
function ping() {
// Reply to sender
this.socket.emit('message', 'PONG!');
});
module.exports = Chat;
Problem
For my REST api I have create a file for each route. ``` app.get('/api/user', routes.user.index); app.get('/api/user/login', routes.user.login); ``` etc, etc. Now I'm introducing socket.io to the backend and it seems I can only call one function for all socket events. ``` var socket = require('./socket/stuff.js'); io.sockets.on('connection', function(sock){ socket.stuff(sock, io); }); ``` How should I break up the `./socket/stuff.js` file (which exports `stuff`). Into separate files. I would like to eventually replace my REST api with sockets, but I don't want everything to be in one file. I imagine I would have: ``` ./socket/chat.js ./socket/user.js ``` etc. etc.