Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
662 views
in Technique[技术] by (71.8m points)

node.js - 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 );
       }
    });
  });
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...