Use WebSocket with Express

const express = require("express");
const ws = require("ws");

const app = express();
const port = process.env.PORT || 3000;
const wsServer = new ws.Server({ path: "/sockethub", noServer: true });

app.get("/", (req, res, next) => {
    res.send("nice to meet you");
});

wsServer.on("connection", (socket) => {
    socket.on("error", console.error);

    socket.on("message", (data) => {
        console.log("received: " + data);
    });

    socket.send("something");
});

const server = app.listen(port, () => {
    console.log(`running at http://localhost:${port}`);
});

server.on("upgrade", (req, socket, head) => {
    wsServer.handleUpgrade(req, socket, head, (socket) => {
        wsServer.emit("connection", socket, req);
    });
});
创建时间:10/31/2023 11:37:35 AM 修改时间:10/31/2023 11:38:05 AM