JavaScript WebSocket 1006错误60秒后

kpbwa7wx  于 2023-10-20  发布在  Java
关注(0)|答案(1)|浏览(209)

我正在尝试用websockets和JavaScript做一个小的在线浏览器游戏,但是websockets在60秒后关闭,错误代码为1006,没有原因(onerror没有被调用),尽管我每5秒就有一个乒乓请求。我可以用这段代码复制它:

// server.js

const ws = require("ws")
const { createServer } = require("http")

const server = new ws.Server({ noServer: true })

createServer((req, res) => {
    server.handleUpgrade(req, req.socket, Buffer.alloc(0), (socket, req) => {
        socket.on("message", (message) => {
            if (message == "Ping")
                socket.send("Pong")

            console.log(message.toString())
        })

        socket.on("close", () => {
            console.log("closed")
        })

        socket.on("error", (err) => {
            throw err;
        })
    })
}).listen(8000, "127.0.0.1")

<!--- index.html --->

<!DOCTYPE html>
<html>
    <body>
        <script>
            var ws = new WebSocket("ws://127.0.0.1:8000");
            ws.onopen = (ev) => {
                ws.send("Hello, Server!");

                ws.onmessage = (ev) => {
                    console.log(ev.data);
                }
                
                ws.onclose = (ev) => {
                    console.log(`Closed ${ev.code} : ${ev.reason}`);
                }

                ws.onerror = (err) => {
                    console.log(err);
                }

                (async () => {
                    function sleep(ms) {
                        return new Promise(resolve => setTimeout(resolve, ms));
                    }

                    while (ws.readyState == 1) {
                        ws.send("Ping");
                        await sleep(5000);
                    }
                })();
            }
        </script>
    </body>
</html>

我试图降低乒乓睡眠,但它似乎没有做任何事情,仍然关闭后,正好60秒。它在Chrome、Firefox、Opera和Edge浏览器中出错。

k10s72fa

k10s72fa1#

我真的不能说为什么服务器会失败,我不知道节点http的内部工作原理-我怀疑是因为它的工作方式,http代码认为没有数据通过套接字,所以最终将其关闭为inactive
备选案文1:
稍微复杂一点,但工作正常-使用这种方法,您实际上可以在一台服务器上实现多个WebSocket(参见示例 * 多个服务器共享单个HTTP/S服务器 *,如ws npm页面所述

const wss1 = new ws.Server({ noServer: true });
wss1.on("connection", (socket) => {
    console.log("wss1 connection");
    socket.on("message", (message) => {
        if (message == "Ping") {
            socket.send("Pong");
        }
        console.log(message.toString());
    });
    socket.on("close", () => {
        console.log("closed");
    });
});

const server = createServer();
server.on("upgrade", (req, socket, head) => {
    wss1.handleUpgrade(req, socket, head, (ws) => {
        wss1.emit("connection", ws, req);
    });
});
server.listen(8000, "127.0.0.1");

备选案文2:
非常简单的代码

const server = createServer();

const wss = new ws.Server({ server });

wss.on("connection", (socket) => {
    console.log("wsServer connection");
    socket.on("message", (message) => {
        if (message == "Ping") {
            socket.send("Pong");
        }
        console.log(message.toString());
    });
    socket.on("close", () => {
        console.log("closed");
    });
});
server.listen(8000, "127.0.0.1");

相关问题