socket.to(socket.id).emit(...) does not emit to himself
See original GitHub issueYou want to:
- report a bug
- request a feature
Current behaviour
We are developing a card game for Android. We have a lobby system. When every player in the lobby is ready the game will start. The client who last send the ready-event triggers the startGame()
function, which first generates the cards for all clients and then sends the client’s card deck to them. Following source code is handling the sending to the clients:
dealCards(socket) {
for (let i = 0; i < this.getNumPlayers; i++) {
// get playercards out of the card deck
let cards = [];
for (let j = i; j <= this.cardDeck.length - (this.getNumPlayers - i); j += this.getNumPlayers) {
cards.push(this.cardDeck[j]);
}
this.players[i].setCards(cards);
// emit cards to player
socket.to(this.players[i].getSocketId).emit(EVENT.LOBBY.START_GAME, {
cards: cards,
});
}
}
But the client who triggered startGame()
is not receiving the start_game-event. When we emit the event like in the following source code it works:
dealCards(socket) {
for (let i = 0; i < this.getNumPlayers; i++) {
[...]
// emit cards to player
if (this.players[i].getSocketId === socket.id) {
socket.emit(EVENT.LOBBY.START_GAME, {
cards: cards,
});
} else {
socket.to(this.players[i].getSocketId).emit(EVENT.LOBBY.START_GAME, {
cards: cards,
});
}
}
}
Steps to reproduce
A failing and working testing case can be found here.
- start the server
npm run client
- start some clients in different consoles to fill the ‘lobby’
npm run client
- point your browser to http://localhost:3000
After pressing the button Trigger Error`` you should see a log message at client's cosnole but not in the browser sonsole. After pressing the button
Trigger Working` you should see a log message in all clients console.
Expected behaviour
When using socket.to(id).emit(...)
the event should be emitted to the calling socket too. So in my opinion:
// sending to individual socketid (private message)
socket.to(socket.id).emit('hey', 'I just met you');
should act like:
// sending to the client
socket.emit('hey', 'I just met you');
Setup
- OS: macOS 10.13.1 (Node v8.9.1), Debian 8 (Node v6.11.3)
- Android Client: 1.0.0
- socket.io version: 2.0.3
Issue Analytics
- State:
- Created 6 years ago
- Comments:7 (1 by maintainers)
Top GitHub Comments
@TimmePfeife I added a note in the documentation: https://socket.io/docs/emit-cheatsheet/
I’m closing this now, please do not hesitate if you see any further improvement: https://github.com/socketio/socket.io-website.
I just figured this out the docs are wrong
socket.to(socket.id).emit('hey', 'i just met you')
should actually besocket.emit(('hey', 'i just met you')
where socket is the parent socket