0

i am new to socket.io & nodejs. i have been writing a tictactoe game and i have a problem in it, my purpose is if someone refresh the page or close the browser let his/her opponent know . i know i should do this with disconnect event and here is what i try, but it is not working .

server side

socket.on('disconnect', function() {
    socket.emit('user:disconnect');
});

client side

socket.on('user:disconnect', function() {
    var message = player.getPlayerName() + ' leaves';
    socket.emit('gameEnded', {room: this.getRoomId(), message: message,id:player.getPlayerId(),gameid: this.getGameId(),winType:"leave"});
});

also, i need to know how to get the room of disconnected user . i already saw this but i just want to send the users in a room not all users in the whole application.

Vishnu
  • 11,614
  • 6
  • 51
  • 90
  • Possible duplicate of [Send response to all clients except sender](https://stackoverflow.com/questions/10058226/send-response-to-all-clients-except-sender) – mdziekon Aug 11 '17 at 14:18

1 Answers1

1

server.js

socket.on('disconnect', function() {
    socket.emit('user:disconnect');
});

In the above code if a user named 'xxx' is disconnected, server is emitting 'user:disconnect' to the same user. You have to find the socket connection of other player and emit the event to that client.

You can achieve your goal by joining both the clients in a room and send message to other user in the room.

socket.join('room1');

io.sockets.in('room1').emit('user:disconnect');

Otherwise you have to store all clients as mentioned below and send message to the specific client using the following code.

var users = {
    'client1': [socket object],
    'client2': [socket object],
    'client3': [socket object]
}

users['client3'].emit('user:disconnect')
Vishnu
  • 11,614
  • 6
  • 51
  • 90