简体   繁体   中英

Failed to load resource: the server responded with a status of 426 (Upgrade Required)

I tried to go with the tutorial of this link http://web-engineering.info/node/57

But when I execute node server.js and open the browser http://localhost:3434 it says upgrade required. The server.js file is:

var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({port: 3434});
wss.broadcast = function (data) {
  var i = 0, n = this.clients ? this.clients.length : 0, client = null;
  for (; i < n; i++) {
    client = this.clients[i];
    if (client.readyState === client.OPEN) {
      client.send(data);
    }
    else console.error('Error: the client state is ' + client.readyState);
  }  
};

wss.on('connection', function (ws) {
 ws.on('message', function (message) {
   wss.broadcast(message);
 });
});

you have to open your index.html in browser not http://127.0.0.1:3434 its a websocket server. You are trying to make a http connection to a websocket server.

Most probably your server socket at localhost:3434 don't have support for websocket, so the connection is terminated by the client browser.

This error indicates that on localhost:3434 you are running a HTTP server which is incapable to "upgrade" to websocket.

(Since both simple http and websocket begins with a simple http request. In that http request the client ask the server to switch to websocket protocol.)

Should you add this ?

var ws = require('websocket.io')
  , server = new ws.Server()

// … somewhere in your http server code 
server.on('upgrade', function (req, socket, head) {
  server.handleUpgrade(req, socket, head);
});

ref https://www.npmjs.com/package/websocket.io#passing-in-requests

Check this SO too What is an http upgrade?

I tried intercepting the http request

var ws = require('websocket.io')
      , http = require('http').createServer().listen(3000)
      , server = ws.attach(http)
     
    server.on('connection', function (socket) {
      socket.on('message', function () { });
      socket.on('close', function () { });
    });

https://www.npmjs.com/package/websocket.io#passing-in-requests

For me using the npmjs documentation, I went copy-paste rogue. Then, debugging my client-side request I noted that the URL parameter I was using was not a string as expected.

But it was shark_s's answer that helped remind me to go look at the console and interpret the error again- so thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM