简体   繁体   中英

How do I send data from my route handler to my socket.io function?

How do I send data from my route handler to my socket.io function? My code is as follows:

// Game
app.get('/game', (req, res) => {
    const cookies = req.cookies;
    const currentUser = cookies['current_user'];
    const roomName = cookies['room_name'];

    if (roomName) {
        res.render('pages/game', {
            room: roomName
        });
    } else {
        res.redirect('/login');
    }
});

io.of('/game').on('connection', socket => {
    console.log('a user connected');
    socket.on('disconnect', () => {
        console.log('user disconnected');
    });

    socket.join(roomName);

    io.of('/game').in(roomName).emit('join', currentUser);
    (async() => {
        const sockets = await io.of('/game').in(roomName).fetchSockets();
        console.log(sockets.length);
    })();
});

I would like the socket to join the room defined in the cookie in the route handler above, but I'm not sure how to get the room name into the socket.io function. I considered putting the socket.io stuff in a function and then passing the data as a parameter, but that would cause the same problem as just putting the socket.io stuff inside the route handler, which as I have learnt from these answers is not the right way to do things. Global variables also don't sound like a good idea - multiple users joining would interfere with each other's data. Any help would be greatly appreciated.

You can access the user's cookies by using the socket.handshakes.headers.cookie string. Since this is not an object because it is a header, you need to use the cookie library to convert it into an object.

This is the code that you can use: const cookies = cookie.parse(socket.request.headers.cookie);

Important!

I suggest that you do not use the socket.io-cookie-parser library because has not been updated since 2014 (7 years ago in 2021). However, if you do decide to use it, you must include io.use(cookieParser()); at the top of your code and you can access the cookies from socket.request.cookies or socket.request.signedCookies if using a secret. Please go to the documentation for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM