| 3 | import { Server } from "socket.io"; |
| 4 | |
| 5 | function initServer(port) { |
| 6 | const httpServer = createServer((req, res) => { |
| 7 | if (req.method === "GET" && req.url === "/") { |
| 8 | const content = readFileSync("./index.html"); |
| 9 | res.writeHead(200, { |
| 10 | "content-type": "text/html", |
| 11 | }); |
| 12 | res.write(content); |
| 13 | res.end(); |
| 14 | } else { |
| 15 | res.writeHead(404).end(); |
| 16 | } |
| 17 | }); |
| 18 | |
| 19 | const io = new Server(httpServer, { |
| 20 | cors: { |
| 21 | origin: [ |
| 22 | "http://localhost:3000", |
| 23 | "http://localhost:3001", |
| 24 | "http://localhost:3002", |
| 25 | ], |
| 26 | }, |
| 27 | // TODO use an adapter to broadcast messages between the Socket.IO servers |
| 28 | }); |
| 29 | |
| 30 | io.on("connection", (socket) => { |
| 31 | console.log(`connect ${socket.id}`); |
| 32 | |
| 33 | socket.conn.on("upgrade", (transport) => { |
| 34 | console.log(`transport upgraded to ${transport.name}`); |
| 35 | }); |
| 36 | |
| 37 | socket.on("disconnect", (reason) => { |
| 38 | console.log(`disconnect ${socket.id} due to ${reason}`); |
| 39 | }); |
| 40 | }); |
| 41 | |
| 42 | httpServer.listen(port, () => { |
| 43 | console.log(`server listening at http://localhost:${port}`); |
| 44 | }); |
| 45 | } |
| 46 | |
| 47 | initServer(3000); |
| 48 | initServer(3001); |