Pentotentolento
Pentotentolento

Reputation: 3

Socket.io has some trouble when handling from modules

Hi i am working with socket.io and node.js (express.js). I saw a lot of examples, coding from the app.js file. Now i would like to organize better the code, i would like to have all my sockets.io handlers in other modules/files.

This is what i have now:

app.js

var moduleExports = require('./routes/moduleExports');
app.get('/', function(req, res){
    res.sendfile(path.join(__dirname + '/index.html'));
    io.on('connection', function(socket){
        moduleExports.socketio(io, socket);
    });
});

moduleExports.js

module.exports = {
    init: function(){
        //some other functions

    }, socketio: function(io, socket){

            socket.emit('chat', 'Wellcome!');
            socket.on('chat', function (data) {
                socket.broadcast.emit('chat', data);
                //socket.broadcast.emit('chat', data);
            });
            socket.on('disconnect', function () {
                socket.broadcast.emit('chat', 'Disconnected');
                //socket.broadcast.emit('chat', data);
            });
    }
};

PROBLEM:

If I open 2 different browsers, one browser is for John and one browser is for Doe. If John sends a message, Doe recieve it two times. If I open again a third browser, and send a message from John, Doe and the third browser are reciving three times the message.

I dont know exactly why this happen. I know something is happen with the "moduleExports.js" file. But I need a way to code my socket.io handlers outside of app.js. So i thought this would be a good pattern but it isnt.

By the way, the client code (it works):

<script src="/socket.io/socket.io.js"></script>
var socket = io();
function submit(){
    socket.emit('chat', $('#m').val());
    $('#m').val('');
    return false;
}

Upvotes: 0

Views: 20

Answers (1)

DevAlien
DevAlien

Reputation: 2476

The io.on('connection' you should have it just once in your code, everytime a client connects to your server that event will be thrown, if you have it multiple times I guess it runs more times. What I would do is the the following:

var moduleExports = require('./routes/moduleExports');
io.on('connection', function(socket){
    moduleExports.socketio(io, socket);
});
app.get('/', function(req, res){
    res.sendfile(path.join(__dirname + '/index.html'));
});

Upvotes: 1

Related Questions