javascript – Express + socket.io routing problem

Question:

Hello everyone. This is the task.

There is a server on the express where the socket is initiated. server.js:

...
var app = express();
var initSocket = require('./models/chats');
var groupchat = require('./models/chats/routerMiddle');
var server = http.createServer(app);
var io = initSocket(server);
groupchat = groupchat(io);
app.use('/user-groupchat', groupchat);
...

routerMiddle.js

var express = require('express');
var router = express.Router();
var controllerIO = require('./io');


module.exports = function (io) {
    router.get('/', function (req, res, next) {

        controllerIO(req.user, io);


        res.render('user');
    });

    return router;
}

initsocket.js

module.exports = function (server) {

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


    return io;
};

and the router has an io file connection:

module.exports = function (user, io) {

    io.on('connect', (socket) => {
         console.log('connect');
    });

}

The idea is that during authorization, req.user contains the data of the authorized user, and they partially need to be passed to the socket implementation.

For example,

socket.emit('update', req.user.username);

The described piece of code works. Only when you first log into the router, the username is thrown into the console once. If you refresh the page, the user's name flies twice. And then three. In general, when the controllerIO (req.user, io); function is executed in the router; they multiply.

Can you please tell me how to optimize this whole story? Maybe someone came across? Or at least to avoid duplicate events in the socket when the page is refreshed.

Answer:

found a solution like this: A separate module for the socket is created –

function SocketIO(io) {
    this.io = io;
    this.socket = null;
}

SocketIO.prototype.connect = function () {
    var that = this;
    return new Promise(function (resolve, reject) {
        that.io.on('connect', (socket) => {
            that.socket = socket;
            resolve(that.socket);
        });
    });

};

SocketIO.prototype.emit = function (event, data) {
    this.socket.emit(event, data);
};


SocketIO.prototype.on = function (event, callback) {
    console.log(event, callback);

   this.socket.on(event, callback);
};



module.exports = SocketIO;

Next, it is initiated and called in the dig –

module.exports = function (io) {

    router.get('/', function (req, res, next) {
        let chat = new SocketIO(io);

        chat.connect().then((data)=>{
            controllerIO(req.user, data, chat.io);
        });

        res.render('user', {
            user: req.user
        });
   });

    return router;
}

While everything is alive and working, someone else tried to do this, I will be glad to hear tips on optimization.

Scroll to Top
AllEscort