title: JavaScript: Find Local WebSocket Servers
body: <p>I'm experimenting at the moment with trying to detect local network websocket servers (that I wrote) within an IP range. I have one running on the network and I would like my script to detect it (and others on the same port).</p>
  
  <p>At the moment I can accomplish this with a for loop and just try and create a list depending on whether I can successfully connect to a server on that IP. That however is very slow and inefficient. Any ideas how to do this quickly and efficiently?</p>
  
  <p>A snippet of my code:</p>
  
  <pre><code>var port = 1234;
  var ip_range = "192.168.1.";
  var servers = [];
  var i = 0;
  
  function findServers() {
      if ( i &gt; 255 ) {
          return;
      }
      try {
          var host = "ws://"+ip_range+i+":"+port;
          var socket = new WebSocket(host);
          socket.onopen = function(){
              console.log("Success: " + socket.url);
              servers.push(socket.url);
              i++;
              findServers();
          };
          socket.onerror = function(error){
              console.log("Error: " + socket.url);
              i++;
              findServers();
          };
      } catch (e) {
          console.log("Error: " + socket.url);
          i++;
          findServers();
      }
  }
  </code></pre>
  
  <p>If it helps I wrote the socket server so I can modify the code if need be.</p>