Socket double emits problem in express route (event handler stacking)

醉酒当歌 提交于 2020-08-10 19:36:35

问题


I have problem with stacking socket event handler when hitting express route. I need to reconnect in route then sending emit to specific room.

At first I connect (socket.io) at page X, then connection is lost cause I move to page Y (with use of router.post) and then in router when I reconnect I add new global socket.io handler for the connection event... and cause of that emits are send multiple times.

Ideally, I should use some kind of session to know that user disconnect/connect and be able to recognize him (sending emits to specific room).

INDEX.JS file (main "app" file):

var x = require('./routes/x.js');
var app = express();
app.use('/', x);
app.use(function(req, res, next) {
    req.io = io;
    next();
});
var server = http.createServer(options, app).listen(port, host, function() {
    console.log('Server started!');
});
var io = require('socket.io')(server);

// here we also set rules for socket.io connection:
io.on('connection', function (soc) {
    soc.on('disconnect', function(reason) {
        console.log(reason);
    });
    // soc.on('reconnect', ... etc.
});

route in X.JS file:

var express = require('express');
var app = express();
var router = express.Router();
var request = require('request');

router.post('/Y', function(req, res, next) {
    request(opt, function(err, resp, body) {
        if (resp.statusCode === 200) {
            res.render('Y'); // so the emits can target something (later they build html structure on page 'Y' with proper data, but there must be some structure first)

            function socCon() {
                return new Promise(function(resolve, reject) {
                // so in a route when socket is disconnected and need to be connect again (cause you change location - path) you do it here and it duplicate (just as you said) event handler EVERY time that route is hit:
                    req.io.on('connection', function(socket) {
                        var room = 'room_' + socket.id;
                        socket.join(room);

                        if (socket.join(room)) {
                            resolve(room);
                        }
                        else {
                            reject(console.log('error'));
                        }
                    });
                });
            }

            socCon().then(data).catch(function(error) {
                console.log(error);
            });

            function data(room) {
                req.io.in(room).emit('msg', {emit : 'message'}); // socket.io emits - with use of express route POST on page 'X'
            });
        }
        else {
            res.render('X', {ERRORS : ERRORS});
            res.end(); // do res.end() is needed... after res.render() I guess no...
        }
    });
)};
module.exports = router;

Client page Y:

<!DOCTYPE html>
<html>
<head>
    <title>TITLE</title>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
    socket.on('connect', function() {
        console.log('Connected!');
    });
    socket.on('msg', function(msg) {
        // some HTML mutation here that happened MULTIPLE times causing errors (cause same emit is emitted multiple times)
    });
</script>
</body>
</html>

来源:https://stackoverflow.com/questions/62973624/socket-double-emits-problem-in-express-route-event-handler-stacking

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