Socket.IO disconnection problem before closing window
I am trying to prevent the client from disconnecting from the server. So before the user closes the window on which the app is open, I do:
$(window).bind("beforeunload", function() {
return("Close the app?");
});
But the problem is that no matter if the user chooses to leave or stay on the page where the app is open, the client get's disconnected (stops listening) from the server, before even I chose an option. So if the user chooses开发者_开发知识库 to stay on the page, nothing will be sent or received from the server.
Why can this be? How can this be prevented?
I had exactly the same problem in my project.
When you call socket.connect()
, you should set sync disconnect on unload
parameter of your connection to false
(it is true
by default):
var conn_options = {
'sync disconnect on unload':false
};
socket = io.connect(url, conn_options);
You can find more connection options here: https://github.com/LearnBoost/socket.io/wiki/Configuring-Socket.IO
P.S. Hope it's still actual for you :)
UPD.
Since the doc was changed, false
is now the default value of sync disconnect on unload
You might not be able to avoid the problem as there are no other events triggering before "beforeunload" at window close that i know of. However,you could work around it by asking the socket to reconnect in the callback of the window close dialog when the user chooses to not exit the page. Reconnecting is pretty easy, just:
socket.connect()
Here's another question that describes reconnecting in more detail:
How to reconnect as soon as disconnect happens
精彩评论