繁体   English   中英

io.emit无法发送给所有客户端

[英]io.emit fails to emit to all clients

我试图在一个简单的socket.io游戏中实现“离开游戏”功能,但我不明白为什么io.emit仅通知离开游戏的客户端套接字。 这是我的socket.js代码:

io.on("connection", sock => {

    sock.on('joinGame', name => {
       inc++
       if(name === 'guest') name = name + inc.toString()
       addToGame(inc, name) // adds player to a new Map()
       io.emit('joinedGame', name)   
    })

    sock.on('findPlayersInGame', () => {
       getAllPlayersInGame(io, threeOrMore)
     // check to see if the client is notified when a new user joins
       io.emit('newPlayerJoined', 'new player joined')
    })

    sock.on('leaveGame', name => {
       io.emit('leftGame', uniquePlayers)    
    })

在客户端上,我正在MobX存储中处理套接字通信以及状态管理。 这是我的GameStore.js代码:

export class GameStore {
constructor(aGame) {
    extendObservable(this, {
        players: [],
        game: aGame,
        menuVisibility: true,
        play: action((id, username) => {
            this.menuVisibility = false
            username === undefined ? this.game.setName("guest") : this.game.setName(username)

            // join game with given username
            sock.emit('joinGame', this.game.playerName)

            // after joining, if the username is 'guest' change name to unique guest name provided by server
            sock.on('joinedGame', name => {
                if(this.game.playerName === 'guest') this.game.setName(name)
                console.log(this.game.playerName + " joined the game")
            })
            // populate player list with all players in game room
            this.loadPlayers()
        }),
        quitGame: action(() => {
            //this.menuVisibility = true
            sock.emit('leaveGame', this.game.playerName)
            sock.on('leftGame', players => { // this should be logged to all clients
                console.log('updated player list', players)
                this.players = players
            })
        }),
        loadPlayers: action(() => {
            sock.emit('findPlayersInGame', this.game.playerName)
            sock.on('loadPlayers', players => {
                console.log('loading players...')
                this.players = players
            })
            sock.on('newPlayerJoined', player => {
                console.log(player)
            })
        })   
    })
  }
}

当我调度quitGame动作时,套接字只会向退出游戏的客户端发出信号。 有人离开游戏后,我需要更新商店中的玩家列表,但是我无法弄清楚为什么其他客户端没有收到有人离开游戏的消息。 玩家加入游戏时, io.emit似乎工作正常。

看起来您直到该客户端离开游戏之前都没有注册leftGame消息处理程序。 因此,仍然在游戏中的其他客户端都没有该消息的处理程序。 他们可能正在接收该消息,但是还没有相应的处理程序,因此您看不到它。

移动此代码:

        sock.on('leftGame', players => { // this should be logged to all clients
            console.log('updated player list', players)
            this.players = players
        })

因此,当客户端希望开始接收这些消息时(可能在启动时),它将注册事件处理程序。

暂无
暂无

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

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