1

I want to create a client of socket's io server, where in x and x seconds try make a connection to socket's io server, to verify is server is already up.

What i have in client:

src="http://localhost:90/socket.io/socket.io.js" - load script

var serverStatus = recconectToServer();

        setInterval(function(){

            if (serverStatus) {
                $(".results-server").append("<p style='color:green; width:100%; float:left;'>connection up.</p>");
            } else {
                recconectToServer();
            }
        },3000);


        function recconectToServer() {
            $(".results-server").append("<p style='color:orange; width:100%; float:left;'>try connection.</p>");
            try {
                var socket = new io.connect("http://localhost:90");
                return true;
            } catch(err) {
                $(".results-server").append("<p style='color:red; width:100%; float:left;'>server down.</p>");
                console.log(" Erro = "+ err);
                return false;
            }
        }

Situations:

IF client try to connect when server is down i receive this message: "ReferenceError: io is not defined"

That is normal because server is down, then i start server and client when try make connection (without refresh page) continues receive this message "ReferenceError: io is not defined"

But why this happen?

NOTE: If i execute refresh client page, when server is running, client connect without any problem.

UPDATED: Real problem: the event connected_failed from sockets.io dont work, like others questions that exist in stackoverflow. So for resolve this i did the next solution:

My solution:

<script src="http://localhost:90/socket.io/socket.io.js"></script>
        <script>
            /**
            * timer that try make a new connection to node server
            */
            setInterval(function(){
                if (autoReconnect()) {
                    window.location.href="client.html";
                } else {
                    autoReconnect();
                }
            },5000);

            /**
            * This functions try make connection to node server
            */
            function autoReconnect(){
                try {
                    $.getScript("http://localhost:90/socket.io/socket.io.js");
                    var socket = new io.connect('http://localhost:90');
                    return true;
                } catch(err) {
                    return false;
                }
            }
    </script>

Conclusion: When server become up again, will be redirect to other page, where continue the initial process.

I don't know if this is the best solution, if someone have one better, please tell me.

4

1 に答える 1