Thursday 10 December 2015

Looking for some tips on code organisation with web sockets.

Hey guys!I'm recreating a board game (Dominion) as a node app for learning purposes, using socket.io. I've previously done a chat app, so I think have the basic socket stuff down. The biggest problem I am facing right now, is the organisation of socket code. Until now, everything was in one file. Here's the basic code structure:app.jsrequire('./config/socket.js')(server,sessionStore); ./config/socket.jsmodule.exports = function (server,sessionStore) { var io = require('socket.io').listen(server); var saved_sockets={}; //Expose session to socket io.use(function (socket, next) { ... }); //Socket io.on('connection', function (socket) { //Setup var user=socket.session.chat.user; var userId=socket.session.chat.userId; saved_sockets[user]=socket.id; console.log(' [socket.io] connection: '+user+' ('+saved_sockets[user]+')'); socket.join('lobby'); socket.emit('chat-setup',{user:user}); socket.broadcast.to('lobby').emit('message',{room:'lobby',type:'info',from:'system',message:'The user <'+user+'> joined!'}); //Disconnect socket.on('disconnect',function() { delete(saved_sockets[user]); io.sockets.to('lobby').emit('message',{room:'lobby',type:'info',from:'system',message:'The user <'+user+'> left.'}); }); //EVENTS HERE socket.on('some-event',function(data) { ... stuff ... }); Right now all my events, for the pre-game lobby, chat, game mechanics etc. is all in this file, under "//EVENTS HERE". As you can imagine, the file is starting to get big and I'd like to move parts of the code to different files. Is there a way to do this, maybe similar to having different files for different routes in the express app? Maybe something like:var someEventHandler=require('.../socket_handlers/game_events/someEventHandler.js'); socket.on('some-event',someEventHandler)); Keeping in mind that the handler would somehow need to access 'socket' and other variables that are outside of the file's scope...Thankful for any tips!Have a nice day

Submitted December 10, 2015 at 09:35PM by DJLaMeche

No comments:

Post a Comment