Felix Fong
Felix Fong

Reputation: 985

Socket.io connection keep increasing each time a new connect has been made

I'm using Express4 with a router that points to path /, and that is handled by a JS file named chat.js.

And my IO object is already bind to app.io, so inside my chat.js I'll call my Socket.IO by using req.app.io, but the problem is, I use to be using socket.emit and the code just work fine, but now if I want to sync up with the client I have to using req.app.io.emit.

And since because I'm using req.app.io.emit, I have the connection keep increasing problem.


index.js

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const path = require('path');
const randomstring = require('randomstring');
const sha256 = require('sha256');
const io = require('socket.io').listen(server);
app.io = io;
const port = process.env.PORT || 3000;

module.exports.users = {};

server.listen(port, () => {
    console.log(`Serer is running on port ${port}`);
});

app.set('view engine', 'ejs');
app.set('views', path.join(`${__dirname}/../public`));
app.use('/static', express.static(path.join(`${__dirname}/../public`)));


app.use('/', require('./chat'));

chat.js

const express = require('express');
const router =  express.Router();
const users = require('./index').users;
const randomstring = require('randomstring');
router.get('/', (req, res) => {
    res.render('index');
    const uid = randomstring.generate(30);
    users[uid] = true;
    req.app.io.on('connection', socket => {
        console.log('hello');

        socket.on('disconnect', () => {
            console.log('bye');
        });

    });
});

module.exports = router;

Log(Image)

Serer is running on port 3000
hello
bye
hello
hello
bye
bye

Upvotes: 1

Views: 1995

Answers (1)

jfriend00
jfriend00

Reputation: 707158

Every time your / route is hit, you create a new duplicate io.on('connection', ...) event handler. So, after that route is hit 3 times, you have 3 event handlers for the connection event. So, when it occurs, your code gets called 3 times.

Instead, you should do the io.on('connection', ...) only once outside the route.


FYI, you don't seem to be doing anything useful with the uid you are creating because you don't associate it with any particular connection. FYI, each socket.io connection already has a unique socket.id which is uniquely associated with each socket.io connection so that you can get the id from the socket or can retrieve the socket given only the id.

Upvotes: 2

Related Questions