Jonathan Nielsen
Jonathan Nielsen

Reputation: 1502

Destroy socket.io connection when disconnect

i'm having an issue where a user disconnects from socket.io and the instances remains active, including all event listeners.

Both examples below is partial code of my progress due to hundreds of rows. But the issue remains with this code.

app.js example:

var express = require('express'),
    app = express(),
    routes = require('./routes/index'),
    server = require('http').createServer(app);

io = require('socket.io').listen(server);

app.engine('handlebars', exphbs({ defaultLayout: 'main' }));
app.set('view engine', 'handlebars');

app.use('/', routes);

server.listen(3000, function() {
    console.log('listening on *:3000');
});

module.exports = app;

index.js route example:

var express = require('express'),
    router = express.Router();

router.get('/', function(req, res) {
    res.render('home', {
        title: 'Home'
    });

    setupSocket(req);
});

function setupSocket(req) {
    io.on('connection', function(socket) {
        console.log('connected')
    });
}

module.exports = router;

This will result in:

First connection:

connected

Second connection:

connected
connected

Third connection:

connected
connected
connected

And so on. This will continue on page reload, in a new tab, in a new browser or anything else until i restart the node server.

In my code i'm posting data from client side to a mongo database and due the the issue above, the request will post multiple copies of the same data.

So the question is, how do i prevent the instance to remain active after a user has left the page?

Upvotes: 1

Views: 2790

Answers (1)

Fabio Antunes
Fabio Antunes

Reputation: 22862

As you said on every connection or refresh you are getting multipleconnected strings outputs, that's because you are attaching socket.io listeners on each request. This is how you should attach the connected listener on your socket.io:

var express = require('express'),
    app = express(),
    routes = require('./routes/index'),
    server = require('http').createServer(app);

io = require('socket.io').listen(server);

app.engine('handlebars', exphbs({ defaultLayout: 'main' }));
app.set('view engine', 'handlebars');

app.use('/', routes);

// Your listener should be outside your routes
io.on('connection', function(socket) {
    console.log('connected')
});

server.listen(3000, function() {
    console.log('listening on *:3000');
});

module.exports = app;

And on your index.js just remove the setUp function:

var express = require('express'),
    router = express.Router();

router.get('/', function(req, res) {
    res.render('home', {
        title: 'Home'
    });
});

module.exports = router;

Upvotes: 1

Related Questions