title: PeerJS Auto Reconnect
body: <p>I have recently developed a web app using PeerJS, and am trying to add reconnect functionality.</p>
  
  <p>Basically, my app works by someone creating a <em>server</em> that <em>clients</em> then connect to. The server person can control what the hosts are doing but its basic two way communication.</p>
  
  <p>If a client disconnects they simply reconnect and it works normally. However if the server user refreshes the page, or their computer crashes then they need to be able to re-establish control over the clients. </p>
  
  <p>The start of this is by regaining the original connection ID and peer api ID, which is fine and easy as they are stored in a database and assigned a unique ID the server user can use to query them. Then to enable the client to reconnect I do this upon close:</p>
  
  <pre><code>// connection is closed by the host involuntarily...
  conn.on('close', function() { 
  
      // if the clients connection closes set up a reconnect request loop - when the host takes back control
      // the client will auto reconnect...
  
      connected = false;
      conn = null;
  
      var reconnect_timer = setInterval(function () {
  
          console.log('reconnecting...'); // make a fancy animation here...
          conn = peer.connect(connectionid, {metadata: JSON.stringify({'type':'hello','username':username})});    
  
          // upon connection
          conn.on('open', function() { // if this fails need to provide an error message... DO THIS SOON      
              // run the connect function...
              connected = true;
              connect(conn);      
          });
  
          // didnt connect yet
          conn.on('error', function(err) {
              connected = false;
          });
  
          if(connected === true) {
              clearInterval(reconnect_timer);
          }
  
      }, 1000);
  
  });
  </code></pre>
  
  <p>This appears to work, as on the server end the client looks like they have reconnected - the connect function has fired etc. However messages cant be sent between, and the client console says:</p>
  
  <pre><code>Error: Connection is not open. You should listen for the `open` event before sending messages.(…)
  </code></pre>
  
  <p>Where the 'open' event is shown as having been listened to above...</p>
  
  <p>I hope this is clear - any help is appreciated :) </p>