Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.IO - How to figure out who disconnected?

I'm building simple web application using HTML5 and Javascript on the front end and Node.js on the back end. I'm also using Socket.IO to pass data back and forth between the client and server. Say I have a chat page where everyone signs in and joins a chat room. I keep track of all the people in the chat room on the back end. What I want to do is remove a person from a room if they exit that room. For example say someone closes their browser, they should no longer be shown as an active user.

Socket.IO has a disconnect event which seems to be the perfect tool to do this. For example when I run this code:

socket.on("disconnect", function (){
  console.log("DISCONNECTED");
});

"DISCONNECTED" will be printed when someone closes their browser. Now my question is, how am I supposed to know who exactly closed that browser? No data is passed to the disconnect event, so I'm not sure how exactly I'm supposed to check who set off the disconnect event. Any help would be greatly appreciated!

like image 908
Ben Goldberg Avatar asked Oct 29 '25 06:10

Ben Goldberg


1 Answers

Basically, once you listen the 'connect' event, you will get a socket object whenever a client connect to the server. And you can store client info to that socket object. You can refer to this article, and pay attention to the server side code, where the coder use pluarl form 'sockets' on server side (so server side will create many client socket!). http://psitsmike.com/2011/10/node-js-and-socket-io-multiroom-chat-tutorial/

hope the following sample will help you.

//server side
var io = require('socket.io').listen(80)
// sockets here, not socket
io.sockets.on('connection', function(socket){
  // every connection will create a socket
  socket.on('newUser', function(name){
    socket.id = name; // socket stores the username
  });
  socket.on('disconnect', function(){
    console.log(socket.id); // retrieve it from socket object
  });
  // more functionality goes...
});

and the client side

var socket = io.connect('http://localhost:80');
socket.on('connect', function(){
   //emit newUser event so that client info is stored
  socket.emit('newUser', prompt('Please enter your name!'));
  //.... more functionality goes
});

Hope this will help you understand!

like image 100
Herrington Darkholme Avatar answered Oct 30 '25 23:10

Herrington Darkholme



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!