Sami Sami - 1 year ago 124
Node.js Question

broadcast client disconnect to a particular room

I am following this excellent Tutorial to make my first test game in node.js

Everything is working perfectly. Even when I changed it from two player to three player, still worked fine. But unfortunately the tutorial did not cover the

disconnect event
. Every event on server is happening against some client action. e.g join game, answer click etc.

But i am stuck at broadcasting to all clients in a room when one of the user looses his internet connection because he performs no action to do that. By some search i found something like following

// Listen for Socket.IO Connections. Once connected, start the game logic.
io.sockets.on('connection', function (socket)
//console.log('client connected');
initGame(io, socket);
io.sockets.on('disconnect', function ()
socket.broadcast.emit('playerDisconnected', 'x has disconnected');

This is not working. And I cant understand how to know and how to tell users in a room that who has disccented. Please guide me what i can do more to make question clear.


With the help of given answer I am able to broadcast a disconnect event to all clients connected to the server. But what can i do to emit only to the particular game clients mean from where i could get gameid/roomid in this event. I see something like game socket in my working code/ (following is it). but I tried simple
socket.emit('playerDisconnected', 'x has disconnected');
it does not work and
works but not as i need

function initGame(sio, socket)
io = sio;
gameSocket = socket;
gameSocket.emit('app_ev_connected', { message: "You are connected!" });

gameSocket.on('serv_ev_playerJoinGame', playerJoinGame);

Answer Source

Don't you need to add the disconnect event on the socket itself?

io.sockets.on('connection', function (socket) {

   initGame(io, socket);
   socket.on('disconnect', function () {
      //socket.broadcast.emit('playerDisconnected', 'x has disconnected');
      socket.broadcast.emit('playerDisconnected', + ' has disconnected');
//if you want to emit in particular room'roomName').emit('playerDisconnected', +' has disconnected');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download