为什么node.js在尝试在localhost上运行应用程序时需要升级?

ria*_*zar 10 javascript real-time websocket node.js

当我尝试在localhost服务器上运行我的node.js应用程序时,它不会运行并要求进行必要的升级.我试图运行代码,但我收到以下错误:

截图

服务器代码

 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

客户代码

      <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>
Run Code Online (Sandbox Code Playgroud)

mau*_*der 10

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

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


小智 9

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

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

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

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

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

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