简体   繁体   English

为什么客户端没有收到 socket.io 广播(房间)?

[英]Why is the client not receiving the socket.io broadcast (rooms)?

My client is not receiving the broadcast sent to the room.我的客户没有收到发送到房间的广播。 If I replace socket.to(roomName).emit('join', currentUser);如果我替换socket.to(roomName).emit('join', currentUser); with socket.emit('join', currentUser);socket.emit('join', currentUser); the client receives the broadcast, but I'd like to use rooms here.客户端接收广播,但我想在这里使用房间。 Any help would be greatly appreciated.任何帮助将不胜感激。

app.js

// 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
        });

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

            socket.join(roomName);

            socket.to(roomName).emit('join', currentUser);
        });
    } else {
        res.redirect('/login');
    }
});

game.ejs

const socket = io("/game");

socket.on('join', function(user) {
    console.log(`${user} joined`);
});

Also, could I replace this:另外,我可以替换这个:

if (roomName) {
    // stuff
} else {
    // other stuff
}

with this:有了这个:

if (!roomName) {
    // other stuff
    return;
}
// stuff

According to the documentation , if you use socket.to('room').emit(...) instead of io.in('room').emit(...) , it will be broadcasted to all sockets in the room except the sender .根据文档,如果您使用socket.to('room').emit(...)而不是io.in('room').emit(...) ,它将被广播到房间除了发件人 That's where your problem lies.那就是你的问题所在。

The reason socket.emit(...) works is because you're sending it directly and only to the sender.究其原因socket.emit(...)的工作原理是,因为你直接发送只有它给发件人。

This emit cheatsheet is quite useful to figure out which combinations of io / socket and to etc affect where messages get sent to.这个发出备忘单对于确定io / socketto etc 的哪些组合会影响消息发送到的位置非常有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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