0

我有一个非常简单的 Node.js 服务器,它为 WebSockets 使用“ws”,但它只接受一个客户端,我认为它是一个多客户端服务器。

这就是我现在用来测试它的程序。简短而简单,但不起作用。

const WebSocket = require('ws');
const fs = require('fs');
const https = require('https');

let server = new https.createServer({
    key: fs.readFileSync("./ssl/private.key"),
    cert: fs.readFileSync("./ssl/certificate.crt"),
    ca: fs.readFileSync("./ssl/ca_bundle.crt")
}).listen(443);

let wss = new WebSocket.Server({
    noServer: true
});

server.on("upgrade", (request, socket, head) => {
    wss.handleUpgrade(request, socket, head, (ws) => {
        ws.onopen = (event) => {
            console.log("A client has connected");
        };
        ws.onclose = (event) => {
            console.log("A client has disconnected");
        }
    });
});

两个客户端都在 Google Chrome 中运行相同的代码(也用 firefox 测试过)代码:

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <script>
            var ws = new WebSocket("wss://example.com/ws/");
            ws.onopen = function(e){
                console.log("Open: ", e);
            }
            ws.onmessage = function(e){
                console.log("Message: ", e);
            }
            ws.onerror = function(e){
                console.log("Error: ", e);
            }
            ws.onclose = function(e){
                console.log("Close: ", e);
            }
        </script>
    </body>
</html>

一个客户端将记录打开的连接,每个其他客户端将记录超时、错误和关闭事件。提前致谢

4

0 回答 0