|
| 1 | +import { readFileSync } from "node:fs"; |
| 2 | +import { createServer } from "node:https"; |
| 3 | +import { Server } from "socket.io"; |
| 4 | +import { Http3Server } from "@fails-components/webtransport"; |
| 5 | + |
| 6 | +const key = readFileSync("./key.pem"); |
| 7 | +const cert = readFileSync("./cert.pem"); |
| 8 | + |
| 9 | +const httpsServer = createServer({ |
| 10 | + key, |
| 11 | + cert |
| 12 | +}, (req, res) => { |
| 13 | + if (req.method === "GET" && req.url === "/") { |
| 14 | + const content = readFileSync("./index.html"); |
| 15 | + res.writeHead(200, { |
| 16 | + "content-type": "text/html" |
| 17 | + }); |
| 18 | + res.write(content); |
| 19 | + res.end(); |
| 20 | + } else { |
| 21 | + res.writeHead(404).end(); |
| 22 | + } |
| 23 | +}); |
| 24 | + |
| 25 | +const io = new Server(httpsServer, { |
| 26 | + transports: ["polling", "websocket", "webtransport"] |
| 27 | +}); |
| 28 | + |
| 29 | +const port = process.env.PORT || 3000; |
| 30 | + |
| 31 | +io.on("connection", (socket) => { |
| 32 | + console.log(`connect ${socket.id}`); |
| 33 | + |
| 34 | + socket.conn.on("upgrade", (transport) => { |
| 35 | + console.log(`transport upgraded to ${transport.name}`); |
| 36 | + }); |
| 37 | + |
| 38 | + socket.on("disconnect", (reason) => { |
| 39 | + console.log(`disconnect ${socket.id} due to ${reason}`); |
| 40 | + }); |
| 41 | +}); |
| 42 | + |
| 43 | +httpsServer.listen(port, () => { |
| 44 | + console.log(`server listening at https://localhost:${port}`); |
| 45 | +}); |
| 46 | + |
| 47 | +const h3Server = new Http3Server({ |
| 48 | + port, |
| 49 | + host: "0.0.0.0", |
| 50 | + secret: "changeit", |
| 51 | + cert, |
| 52 | + privKey: key, |
| 53 | +}); |
| 54 | + |
| 55 | +(async () => { |
| 56 | + const stream = await h3Server.sessionStream("/socket.io/"); |
| 57 | + const sessionReader = stream.getReader(); |
| 58 | + |
| 59 | + while (true) { |
| 60 | + const { done, value } = await sessionReader.read(); |
| 61 | + if (done) { |
| 62 | + break; |
| 63 | + } |
| 64 | + io.engine.onWebTransportSession(value); |
| 65 | + } |
| 66 | +})(); |
| 67 | + |
| 68 | +h3Server.startServer(); |
0 commit comments