title: Chrome websockets, readystate always on 0
body: <p>I'm trying to use websockets on a website, so first I developed a small and very simple websocket page just to test it.</p>
  
  <p>I have a websocket server running on my localhost, it is based on the python Tornado "Chat" demo. For some reason the chat demo app runs perfectly but I can't seem to use the websocket  with my own page although some form of connection is made.</p>
  
  <p>I am testing this using the latest Chromium version, so implementing websockets version 13, which is supported by the Tornado implementation.</p>
  
  <p>So here is the problem:</p>
  
  <ol>
  <li>Load page, js executes and Upgrade request is sent to the server</li>
  <li>Server receives request and answers</li>
  </ol>
  
  <p>So here in my understanding Chrome should set readyState = 1 and I should be able to send messages from my page.</p>
  
  <p>Only for some reason it doesn't work, readyState remains 0 and of course if I try to send a message I receive an INVALID_STATE_ERR.</p>
  
  <p>Here are the Headers :</p>
  
  <p>Request:</p>
  
  <pre><code>GET ws://127.0.0.1:8000/chatsocket HTTP/1.1
  Origin: http://127.0.0.1
  Cookie: _xsrf=9f73731fc2d544df864ce777bef0775a
  Connection: Upgrade
  Host: 127.0.0.1:8000
  Sec-WebSocket-Key: pkwlpY+TtxfgUrm3M4WtTQ==
  Upgrade: websocket
  Sec-WebSocket-Version: 13
  </code></pre>
  
  <p>Response:</p>
  
  <pre><code>HTTP/1.1 101 Switching Protocols
  Connection: Upgrade
  Upgrade: websocket
  Sec-WebSocket-Accept: ur9KL2jBhYB38e2SgwOkjyBlQXk=
  </code></pre>
  
  <p>Any help is appreciated :)</p>
  
  <p><br><br></p>
  
  <p>--- EDIT ---</p>
  
  <p><br></p>
  
  <p>So I figured it out in the end, if you run into the same problem here is the reason:</p>
  
  <p><strong>WebSocket's readyState is updated when the Thread ENDS !</strong></p>
  
  <p>So running a code like:</p>
  
  <pre><code>var ws = new WebSocket(stuff);
  while(ws.readyState==0){};
  </code></pre>
  
  <p>Will send the browser in an infinite loop...</p>
  
  <p>Running code like:</p>
  
  <pre><code>var ws=new WebSocket(stuff);
  do_other_stuf();
  </code></pre>
  
  <p>Might work, but you wont be able to use WS.</p>
  
  <p><br></p>
  
  <p>If the code that is supposed to run after the socket opens uses the socket this is the way it will have to be written:</p>
  
  <pre><code>var ws=new WebSocket(stuff);
  ws.onopen = new function(){
      // some code that need WS to be open
  }
  // rest of the code that doesn't require WS to be open
  </code></pre>
  
  <p>A better way to do this would be to let the thread end by using an asynchronous call:</p>
  
  <pre><code>var ws = new WebSocket(stuff);
  setTimeout(whatever,500);
  
  function whatever(){
      if(ws.readyState==1){
          // The code you want to run after WS is open
      }
      else
          setTimeout(whatever,500);
  }
  </code></pre>