Socket.io: How to perform certain actions when reconnecting after disconnecting?

I use node.js and socket.io to create a game.

I have a code as shown below. The game is simple. It starts to do some animation as soon as it connects to the server and it continues the animation.

I want to make sure that the game did not succeed gracefully if the Internet connection is not working or if the server is down. And the game returns after reconnecting.

The animate function retrieves content from the server. Therefore, it will not work properly if there is no connection. I want the animation function to be executed only when there is a connection.

So, I introduced a variable called connected, which should contain the connection status. if conncted = false, I stop the animation.

But now the socket.io problem itself is trying to reconnect several times. How to set binding to false during the reconnection process?

Game.js

var connected = false; $(document).ready(function(){ //connect to socket server socket = io.connect('/gameserver'); socket.on('connect', function() { connected = true; animate(); }); socket.on('disconnect', function() { connected = false; socket.connect(); }); }); function animate() { .... ...... ........ if (( connected ) && (..... )) animate(); } 
+4
source share
1 answer

You can use the following built-in functions to find out the connection status and determine the animation status accordingly:

 socket.on('disconnect', function(){}); // wait for reconnect, hold animation socket.on('reconnect', function(){}); // connection restored, restart animation socket.on('reconnecting', function( nextRetry ){}); //trying to reconnect, hold animation socket.on('reconnect_failed', function(){ message("Reconnect Failed"); });// end animation 

nextRetry indicates the time before it attempts to connect, if this helps to update the user with the status.

In addition, when disconnecting from the server, you do not need to call socket.connect (). Updated status will be available from socket.on ('reconnect'). So just include the call in the animation.

This is only in case of calling socket.disconnect from the client, the connection will not be restored automatically, and therefore socket.connect () will need to be called again.

+2
source

All Articles