JohnWick
JohnWick

Reputation: 5149

Node.JS + Socket.io, moving socket event handlers to external module?

I have a server.js file like this:

var express = require('express'),
    app = express(),
    server = require('http').createServer(app),
    mongoose = require('mongoose'),
    bodyParser = require('body-parser'),
    apiRouter = require('./app/routes/api.js'),
    io = require('socket.io')(server),
    socketEvents = require('./app/modules/socketEvents.js')(io);

//Clears Node Console.
process.stdout.write('\033c');
console.log('Server starting!');

socketEvents.attachEventHandlers();

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.use('/api', apiRouter);
app.use(express.static('public'));

app.use('*', function(req, res, next) {
    //All requests return single page angular application.
    res.sendFile(__dirname + '/public/index.html');
});

mongoose.connect('localhost', 'triviaattack', function(err) {
    if (err) {
        console.log('An error occured when connecting to the MongoDB Database');
        throw err;
    }
});

server.listen(1337);

And socketEvents.js

module.exports = function(io) {

    return {
        attachEventHandlers: function() {

            io.on('connection', function(socket) {

                console.log('client connected');

                socket.on('joinMatchMaking', function(data) {
                    //Every time a player joins the matchmaking queue, check if a game can be created.
                    matchMakingQueue.push(data);
                    var matchedPlayers = [];
                    for (i = 0; i < matchMakingQueue.length; i++) {
                        switch (data.gameType) {
                            case '1v1':
                                matchedPlayers.push(matchMakingQueue[i].username);
                                if (matchedPlayers.length == 2) {
                                    socket.emit('matchFound', {players: matchedPlayers});
                                } 
                                console.log('user joined 1v1 queue');
                            case '2v2':
                                matchedPlayers.push(matchMakingQueue[i].username);
                                if (matchedPlayers.length == 4) {
                                    socket.emit('matchFound', {players: matchedPlayers});
                                } 
                                console.log('user joined 2v2 queue');
                        }
                    }
                    console.log(data.username + ' joined the ' + data.gameType + ' matchmaking queue');
                    console.log('users in queue: ' + matchMakingQueue.length);
                });

                socket.on('leaveMatchMaking', function(username) {
                    matchMakingQueue.splice(matchMakingQueue.indexOf(username), 1);
                    console.log(username + ' left matchmaking queue.');
                    console.log('users in queue: ' + matchMakingQueue.length);
                });

            });

        console.log('events attached');

        }
    }

};

When I load my site in my browser, the io.on('connection), function () {...}) event handler is not being called, which should output a console.log message whenever a client connects. I want to keep my socket.io events outside of my main server.js file because there will be alot of them and I wanted to separate them into their own module.

Upvotes: 0

Views: 1260

Answers (2)

Connor
Connor

Reputation: 1855

I do this by stuffing all of my socket events in a middleware:

var io = require('socket.io');
// listen stuff
var SocketEvents = require('./socket-events.js')(io);
io.use(SocketEvents);

... and then in socket-events.js something like:

module.exports = function(io) {
    return function(socket, next) {
        // do stuff
        return next();
    }
}

I should add that in this case the on("connection") listener appears not to be necessary, as each middleware function is executed on each incoming socket connection already.

Upvotes: 1

Brian Baker
Brian Baker

Reputation: 996

You need to have some socket code in the html file to connect.. can you include it as well?

Upvotes: 2

Related Questions