|
| 1 | +const cluster = require("cluster"); |
| 2 | +const { createServer, Agent } = require("http"); |
| 3 | +const { Server } = require("socket.io"); |
| 4 | +const { setupMaster, setupWorker } = require("../.."); |
| 5 | +const assert = require("assert").strict; |
| 6 | +const { sendRequest } = require("./util"); |
| 7 | + |
| 8 | +if (cluster.isWorker) { |
| 9 | + const httpServer = createServer(); |
| 10 | + const io = new Server(httpServer); |
| 11 | + setupWorker(io); |
| 12 | + |
| 13 | + io.on("connection", (socket) => { |
| 14 | + socket.on("foo", (val) => { |
| 15 | + socket.emit("bar", val); |
| 16 | + }); |
| 17 | + }); |
| 18 | + |
| 19 | + return; |
| 20 | +} |
| 21 | + |
| 22 | +const WORKER_COUNT = 3; |
| 23 | + |
| 24 | +for (let i = 0; i < WORKER_COUNT; i++) { |
| 25 | + cluster.fork(); |
| 26 | +} |
| 27 | + |
| 28 | +const httpServer = createServer(); |
| 29 | + |
| 30 | +setupMaster(httpServer, { |
| 31 | + loadBalancingMethod: process.env.LB_METHOD || "least-connection", |
| 32 | +}); |
| 33 | + |
| 34 | +httpServer.listen(async () => { |
| 35 | + const port = httpServer.address().port; |
| 36 | + |
| 37 | + const agent1 = new Agent({ keepAlive: true }); |
| 38 | + const agent2 = new Agent({ keepAlive: true }); |
| 39 | + |
| 40 | + // Engine.IO handshake on connection 1 |
| 41 | + const res1 = await sendRequest({ |
| 42 | + agent: agent1, |
| 43 | + port, |
| 44 | + method: "get", |
| 45 | + path: "/socket.io/?EIO=4&transport=polling", |
| 46 | + }); |
| 47 | + |
| 48 | + assert.equal(res1.statusCode, 200); |
| 49 | + |
| 50 | + const sid = JSON.parse(res1.body.toString().substring(1)).sid; |
| 51 | + |
| 52 | + // Engine.IO handshake on connection 2 |
| 53 | + const res2 = await sendRequest({ |
| 54 | + agent: agent2, |
| 55 | + port, |
| 56 | + method: "get", |
| 57 | + path: "/socket.io/?EIO=4&transport=polling", |
| 58 | + }); |
| 59 | + |
| 60 | + assert.equal(res2.statusCode, 200); |
| 61 | + |
| 62 | + // Socket.IO handshake on connection 2 |
| 63 | + const res3 = await sendRequest( |
| 64 | + { |
| 65 | + agent: agent2, |
| 66 | + port, |
| 67 | + method: "post", |
| 68 | + path: `/socket.io/?EIO=4&transport=polling&sid=${sid}`, |
| 69 | + }, |
| 70 | + "40" |
| 71 | + ); |
| 72 | + |
| 73 | + // FIXME "session ID unknown" |
| 74 | + assert.equal(res3.statusCode, 400); |
| 75 | + |
| 76 | + // cleanup |
| 77 | + for (const id in cluster.workers) { |
| 78 | + cluster.workers[id].kill(); |
| 79 | + } |
| 80 | + httpServer.close(); |
| 81 | +}); |
0 commit comments