Y
Y
Yuri Matveenko2018-05-19 18:27:18
Socket.io
Yuri Matveenko, 2018-05-19 18:27:18

When refreshing the page, io.on('connection') is fired multiple times. Why?

const models = require('../models/models.js');
const path = require('path');
let user = false;




module.exports = function (app,passport,io, req, res) {
    let users={};
    let keys={};


    io.on('connection', function(socket){
        user = req.user;

        console.log('Пользователь ' + user.email + ' подключился!');

        users[user.email] = socket.id;
        keys[socket.id] = user.email;

        //Отлючение пользователя
        socket.on('disconnect', function(){
            console.log('Отлючение ' + user.email);
            delete users[keys[socket.id]];
            delete keys[socket.id];
        });
    });

};

That is, when I open the page, I see in the console:
The user user has connected!

When refreshing the page:

disable user


The user user has connected!
The user user has connected!

When you re-update 2 shutdowns, 3 connections,
then 3 disconnections 4 connections. and so on
. I connected the controller in which I have io.connect like this:
app.get('/chat', isLoggedIn, function(req, res) {
        require('./controller/controller.js')(app,passport,io, req, res);
        res.render('chat.ejs');
    });

Why does socket.io call connect callback multiple times after page reload?
Here is the same. But there is no answer

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Aksentiev, 2018-05-19
@Sanasol

Each time a connection is made, a new disconnect listener is created.
At a minimum, it must be pulled out of on('connection').
On the client, it is similar to check that there are no on () in others.
And of course, connecting the module with each request adds event listening every time.
Very strange code, why everything is mixed together and the socket server and the normal server.
Take out the socket server separately. On the route, only give the layout with scripts.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question