Best way for a client to wait for web layouts?

I would like to connect to the server and then do some things as soon as the connection is open. But if the connection stops, I want to trap and not do this, and possibly cancel the pending connection.

function doStuff () {
    var connection = new WebSocket('wss://someURL');

    //do some stuff here as soon as socket open but trap for stall
}

I was looking for some features like

connection.addEventListener('timeout',...);

since when setting up my WS server I don’t respond (simulate a server that is too slow), the Chrome Network Inspector constantly shows the connection as "Waiting". Due to the lack of this feature, my first pass:

function doStuff () {
    var connection = new WebSocket('wss://someURL');
    connection.addEventListener('open', onOpen, false);

    var socketTimer = setTimeout(onNotResponding, 10000);

    function onOpen () {
        clearTimeout(socketTimer);
        //do my stuff here.
    }

    function onNotResponding () { 
        //the server is not responding, how do I "cancel" the connection request here? 
    }
}
+4
source share
3 answers

( : -... , , , . , , , ).

:

var socket;

var socketOnMessage = function(msg) {
    console.log("received " + msg.data);
};

var socketOnOpen = function(msg) {
    console.log("websocket opened");
};

var socketOnClose = function(msg) {
    console.log('websocket disconnected - waiting for connection');
    websocketWaiter();
};

function websocketWaiter(){
    setTimeout(function(){
        socket = new WebSocket(websocketUrl);
        socket.onopen = socketOnOpen;
        socket.onclose = socketOnClose;
        socket.onmessage = socketOnMessage;
    }, 1000);
};

websocketWaiter();

onClose websocketWaiter.

websocketWaiter , .

+2

, , Chrome Developer Tools, http-, , - . .

To do this, you can install the free WireShark network traffic sniffer, considering this solution here:

How to debug websites using wirehark

You can also filter to show only WebSocket packets using the display filter: (websocket)

-1
source

All Articles