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

故事扮演 提交于 2021-01-28 07:41:28

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/44534393/socket-io-connection-keep-increasing-each-time-a-new-connect-has-been-made

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!