The best way for a client to wait for a websocket?

javascript, websocket

Solution

(This is an answer to the question: the best way to wait for a websocket ... to become available, which I thought was the intention of this post. Anyway, I'm leaving my answer here, perhaps other readers will find it useful).

Here is how I solved it:

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();

In the onClose event handler, you call the websocketWaiter again.

In websocketWaiter, you must re-initialize the event handlers, because you created a new object.

Problem

I'd like to connect to a server, then do some stuff as soon as the connection is open. But if the connection stalls, I want to trap for that and not do the stuff, and perhaps cancel the waiting 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 feature such as ``` connection.addEventListener('timeout',...); ``` because upon configuring my WS server to not respond (simulate a too slow server), Chrome's network inspector perpetually shows the connection as "Pending". For lack of that feature, my first pass is: ``` 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? } } ```

Original source

Related problems