Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i handle Close event in Socket.io?

I'm making simple online game which based on Web. the game uses Socket.io for netwoking each other. but I encountered the problem.

think about following situation . I ran Socket.io server. one player making the room , and other player join the room. they played game some time .. but one player so angry and close the game tab.

in this situation , how can I get the event which one client have been closed the browser in server-side ?

according to googling , peoples say like this : "use browser-close event like onBeforeUnload"

but I know that All browser don't support onBeforeUnload event. so i want solution about checking the client disconnection event in SERVER SIDE.

in Socket.io ( nodeJS ) server-side console , when client's connection closed , the console say like following :

debug - discarding transport

My nodeJS version is 0.4.10 and Socket.io version is 0.8.7. and both are running on Linux.

Anyone can help please ?

shortend codes are here :

var io = require ( "socket.io" ).listen ( 3335 );
io.sockets.on ( "connection" , function ( socket )
{
  socket.on ( "req_create_room" , function ( roomId ) 
  {
    var socketInstance = io
    .of ( "/" + roomId )
    .on ( "connection" , function ( sock )
    {
       sock.on ( "disconnect" , function () 
       {
          // i want this socket data always displayed...
          // but first-connected-client doesn't fire this event ..
          console.log ( sock );
       }
    });
  });
});
like image 896
Jindong Jung Avatar asked Jan 31 '12 10:01

Jindong Jung


1 Answers

Update: I created a blog post for this solution. Any feedback is welcome!

I recommend using the 'sync disconnect on unload' option for Socket IO. I was having similar problems, and this really helped me out.

On the client:

var socket = io.connect(<your_url>, {
'sync disconnect on unload': true });

No need to wire in any unload or beforeunload events. Tried this out in several browsers, and its worked perfectly so far.

like image 92
Carlos Atencio Avatar answered Sep 21 '22 15:09

Carlos Atencio