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:
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>
The single-threaded implementation makes Node a bad choice for CPU-intensive programs. When a time-consuming task is running in the program it blocks the event loop from moving forward for a longer period.
Node. js is easily employed as a server-side proxy where it can handle a large amount of simultaneous connections in a non-blocking manner. It's especially useful for proxying different services with different response times, or collecting data from multiple source points.
Not Suitable for Heavy-Computing Apps Node. js doesn't support multi-threaded programming yet. It is able to serve way more complicated applications than Ruby, but it's not suitable for performing long-running calculations. Heavy computations block the incoming requests, which can lead to decrease of performance .
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.
Do not open a client HTML file as a localhost URL but open the file directly.
After running your web-socket server,
localhost:[port]/client.html
-> you will get the message "upgrade required".
file:///[folder]/client.html
-> you can see your HTML file.
because you don't have any web-server with a web-socket or you did not configure your web server for your web-socket. So, you should use your file system.
The easiest way is to use right click on the client file and open it with your favorite browser.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With