Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retry socket.io connection if client page loads and server is down

Tags:

socket.io

I'm using SocketIO in a LAN application.

If the client starts and the server is off, how can I make it keep retrying the connection?

The "connect_failed" event doesn't fire because I get an GET error in socket.io: "http://172.20.2.10:8080/socket.io/1/?t=1348654723279"

So I tried:

 var socket = io.connect('172.20.2.10',{port:8080});    
 var connected = false;

    socket.on('connect',function(){                                
                    connected = true;
                });
    socket.on('error', function (err) {
                    reconnect();
                });

    function reconnect(){
                    if (!connected){
                        var t = setTimeout( function() {
                            socket = io.connect('172.20.2.10',{port:8080});
                            reconnect();
                            console.log("Socket REC");
                        },1000);

                    }
                }

But it doesn't reconnect, I think it's because of the JS error...

I'm trying to avoid a page refresh if possible.

like image 312
rspena Avatar asked Sep 26 '12 10:09

rspena


1 Answers

we can manually use reconnect method of socket instance.

socket.on('error', function (err) {
socket.socket.reconnect();
});
like image 170
Kevin Avatar answered Jan 01 '23 23:01

Kevin