Why node.js requires an upgrade while trying to run an application on the localhost?

riadh zar picture riadh zar · Feb 29, 2016 · Viewed 16.3k times · Source

When I try to run my node.js application on a localhost server, it does not run and demands a required upgrade. I have tried to run the code but I get the following error:

screenshot

server code

 var WebSocketServer = require('ws').Server,
    ws = new WebSocketServer({port: 80}),
    CLIENTS=[];


**new connection etablished**
 ws.on('connection', function(conn) {
         CLIENTS.push(conn);
         conn.on('message', function(message) {
         console.log('received:  %s', message);
         sendAll(message);

    });


 console.log("new connection");
         conn.send("NOUVEAU CLIENT CONNECTE");

                **if you close connection**
         conn.on('close', function() {
           console.log("connection closed");
           CLIENTS.splice(CLIENTS.indexOf(conn), 1);
         });

    });
    **send messeages vers all clients**

function sendAll (message) {
    for (var i=0; i<CLIENTS.length; i++) {
      var j=i+1;
      CLIENTS[i].send("Message pour le client "+j+": "+message);
    }
}

client code

      <p>
        Result :<output name="" type="text" id="result" value"readonly"></output>
      </p>
      <input type="text" onchange="ws.send(this.value);">
      </body>
      <script>
          var ws =new WebSocket('ws://localhost:80');
          ws.onmessage=function(event){
              document.getElementById("result").value=event.data;
          }
      </script>

Answer

mauricioschneider picture mauricioschneider · Feb 29, 2016

Upgrade Required is a reference to the header that is sent when establishing a WebSocket connection between a client (i.e. the browser) and the server.

Like @Prinzhorn stated in his comment, you need a client application that connects to your WebSockets server, which could be a static html page. I recommend you reading this introduction to websockets to understand better how WebSockets work.