title: Correct way to handle Websocket
body: <p>I've a client to server Websocket connection which should be there for 40 seconds or so. Ideally it should be forever open.</p>
  
  <p>The client continually sends data to server and vice-versa.</p>
  
  <p>Right now I'm using this sequence:</p>
  
  <pre><code>var socket;
  function senddata(data)
  {
  
      if (!socket)
      {
          socket = new WebSocket(url);
          socket.onopen = function (evt) {
  
              socket.send(data);
  
              socket.onmessage = function (evt) {
                  var obj = JSON.parse(evt.data);
  
                  port.postMessage(obj);
              }
  
              socket.oneerror = function (evt) {
                  socket.close();
                  socket = null;
              }
             socket.onclose = function(evt){
                 socket = null;
             }
  
  
          }
      }
      else
      {
          socket.send(data);
      }
  
  }
  </code></pre>
  
  <p>Clearly as per current logic, in case of error, the current request data may not be sent at all.</p>
  
  <p>To be frank it sometimes gives error that websocket is still in connecting state. This connection breaks often due to networking issues. In short it does not work perfectly well.</p>
  
  <p>I've read a better design : <a href="https://stackoverflow.com/questions/13546424/how-to-wait-for-a-websockets-readystate-to-change">How to wait for a WebSocket&#39;s readyState to change</a> but does not cover all cases I need to handle.</p>
  
  <p>Also I've Googled about this but could not get the correct procedure for this.</p>
  
  <p><strong>So what is the right way to send regular data through Websockets which handles well these issues like connection break etc?</strong></p>