[英]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.