Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for a WebSocket's readyState to change

I'm trying to implement a WebSocket with a fallback to polling. If the WebSocket connection succeeds, readyState becomes 1, but if it fails, readyState is 3, and I should begin polling.

I tried something like this:

var socket = new WebSocket(url); socket.onmessage = onmsg; while (socket.readyState == 0) { } if (socket.readyState != 1) {     // fall back to polling     setInterval(poll, interval); } 

I was expecting socket.readyState to update asynchronously, and allow me to read it immediately. However, when I run this, my browser freezes (I left it open for about half a minute before giving up).

I thought perhaps there was an onreadyStateChanged event, but I didn't see one in the MDN reference.

How should I be implementing this? Apparently an empty loop won't work, and there is no event for this.

like image 916
Kendall Frey Avatar asked Nov 24 '12 22:11

Kendall Frey


People also ask

How do I check my WebSocket connection status?

In the search field, enter websocket . From the search results, click WebSocket Connection Status.

What event occurs when a socket is opened?

Once the connection has been established between the client and the server, the open event is fired from Web Socket instance. It is called as the initial handshake between client and server. The event, which is raised once the connection is established, is called onopen.

Is WebSocket a protocol?

1.7.The WebSocket protocol is an independent TCP-based protocol. Its only relationship to HTTP is that its handshake is interpreted by HTTP servers as an Upgrade request. By default the WebSocket protocol uses port 80 for regular WebSocket connections and port 443 for WebSocket connections tunneled over TLS [RFC2818].


1 Answers

This is simple and it work perfectly... you can add condition about maximal time, or number of try to make it more robust...

function sendMessage(msg){     // Wait until the state of the socket is not ready and send the message when it is...     waitForSocketConnection(ws, function(){         console.log("message sent!!!");         ws.send(msg);     }); }  // Make the function wait until the connection is made... function waitForSocketConnection(socket, callback){     setTimeout(         function () {             if (socket.readyState === 1) {                 console.log("Connection is made")                 if (callback != null){                     callback();                 }             } else {                 console.log("wait for connection...")                 waitForSocketConnection(socket, callback);             }          }, 5); // wait 5 milisecond for the connection... } 
like image 67
user3215378 Avatar answered Sep 28 '22 10:09

user3215378