【问题标题】:Failed to load resource: the server responded with a status of 426 (Upgrade Required)加载资源失败:服务器响应状态为 426(需要升级)
【发布时间】:2020-08-23 06:28:47
【问题描述】:

我尝试使用此链接的教程http://web-engineering.info/node/57

但是当我执行 node server.js 并打开浏览器http://localhost:3434 时,它说需要升级。 server.js 文件是:

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);
 });
});

【问题讨论】:

    标签: node.js websocket webrtc


    【解决方案1】:

    你必须在浏览器中打开你的 index.html 而不是http://127.0.0.1:3434 它是一个 websocket 服务器。您正在尝试与 websocket 服务器建立 http 连接。

    【讨论】:

      【解决方案2】:

      很可能您在 localhost:3434 的服务器套接字不支持 websocket,因此连接被客户端浏览器终止。

      此错误表明您在 localhost:3434 上运行的 HTTP 服务器无法“升级”到 websocket。

      (因为简单的http和websocket都是从一个简单的http请求开始的。在那个http请求中,客户端要求服务器切换到websocket协议。)

      【讨论】:

        【解决方案3】:

        你应该添加这个吗?

        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);
        });
        

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

        也检查这个 SO What is an http upgrade?

        【讨论】:

          【解决方案4】:

          我尝试拦截http请求

          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

          【讨论】:

            猜你喜欢
            • 2021-08-26
            • 2020-02-14
            • 2016-11-01
            • 2018-01-29
            • 2018-12-16
            • 2020-07-04
            • 2021-04-12
            相关资源
            最近更新 更多