我正在尝试在一个简单的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
似乎工作正常。
答案 0 :(得分:1)
在此客户端离开游戏之前,您似乎没有注册leftGame
消息处理程序。因此,仍然在游戏中的其他客户端都没有该消息的处理程序。他们可能正在接收消息,但还没有处理器,所以你看不到它。
移动此代码:
sock.on('leftGame', players => { // this should be logged to all clients
console.log('updated player list', players)
this.players = players
})
以便在客户端想要开始接收这些消息时(可能在启动时)注册事件处理程序。