io.emit无法向所有客户端发出

时间:2017-06-10 23:00:05

标签: javascript node.js reactjs socket.io mobx-react

我正在尝试在一个简单的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似乎工作正常。

1 个答案:

答案 0 :(得分:1)

在此客户端离开游戏之前,您似乎没有注册leftGame消息处理程序。因此,仍然在游戏中的其他客户端都没有该消息的处理程序。他们可能正在接收消息,但还没有处理器,所以你看不到它。

移动此代码:

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

以便在客户端想要开始接收这些消息时(可能在启动时)注册事件处理程序。