为什么 Node.js 在尝试在本地主机上运行应用程序时需要升级?

问题描述 投票:0回答:4

当我尝试在本地主机服务器上运行 Node.js 应用程序时,它无法运行并需要进行必要的升级。我尝试运行代码,但出现以下错误:

screenshot

服务器代码

 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("NEW CLIENT CONNECTED");

         // if you close the connection
         conn.on('close', function() {
           console.log("connection closed");
           CLIENTS.splice(CLIENTS.indexOf(conn), 1);
         });
       
    });
    // send messeages to 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);
    }
}
                    

客户端代码

      <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>
javascript node.js websocket real-time
4个回答
16
投票

Upgrade Required
是对在客户端(即浏览器)和服务器之间建立 WebSocket 连接时发送的标头的引用。

就像 @Prinzhorn 在他的评论中所述,您需要一个连接到 WebSockets 服务器的客户端应用程序,该服务器可以是静态 html 页面。我建议您阅读 websockets 简介,以更好地了解 WebSocket 的工作原理。


11
投票

不要将客户端 HTML 文件作为本地主机 URL 打开,而是直接打开该文件。

运行网络套接字服务器后,

localhost:[port]/client.html
-> 您将收到“需要升级”消息。

file:///[folder]/client.html
-> 您可以看到您的 HTML 文件。

因为您没有任何带有 Web 套接字的 Web 服务器,或者您没有为 Web 套接字配置 Web 服务器。所以,你应该使用你的文件系统。

最简单的方法是右键单击客户端文件并使用您喜欢的浏览器打开它。


0
投票

您需要将基于 WebSocket 的服务器和静态 html 生成器 Express 结合起来。 例如

var express = require('express')
var expressWs = require('express-ws')

var app = express()
expressWs(app)

app.ws('/echo', (ws, req) => {

    ws.on('connection', function (connection) {
        //...
    })

    ws.on('close', function () {
        //...
    })
})

app.use(express.static('public'))
app.listen(3000, function () {
    console.log('Example app listening on port 3000!')
})

在客户端代码中

var ws = new WebSocket('ws://localhost:3000/echo');
ws.onmessage=function(event){
   document.getElementById("result").value=event.data;
}

0
投票

问题是您的 Web 套接字服务器运行在端口 80 上,因此当您使用浏览器打开 html 模板时,您实际上是在打开 Web 套接字服务器。这是因为浏览器打开的网页默认使用80端口。

要解决此问题,请将 Web 套接字服务器的端口设置为其他值,例如 3000。

ws = new WebSocketServer({port: 3000})

然后,当您在浏览器中打开页面时,它将打开实际的 html 页面,而不是 Web 套接字服务器。

© www.soinside.com 2019 - 2024. All rights reserved.