aboutsummaryrefslogtreecommitdiff
path: root/bench/websocket-server/chat-server.bun.js
blob: b015dec7e624b130bcf218ecf99f726abffbdc54 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// See ./README.md for instructions on how to run this benchmark.
const CLIENTS_TO_WAIT_FOR = parseInt(process.env.CLIENTS_COUNT || "", 10) || 16;
var remainingClients = CLIENTS_TO_WAIT_FOR;
const COMPRESS = process.env.COMPRESS === "1";
const port = process.PORT || 4001;

const server = Bun.serve({
  port: port,
  websocket: {
    open(ws) {
      ws.subscribe("room");

      remainingClients--;
      console.log(`${ws.data.name} connected (${remainingClients} remain)`);

      if (remainingClients === 0) {
        console.log("All clients connected");
        setTimeout(() => {
          console.log('Starting benchmark by sending "ready" message');
          ws.publishText("room", `ready`);
        }, 100);
      }
    },
    message(ws, msg) {
      const out = `${ws.data.name}: ${msg}`;
      if (ws.publishText("room", out) !== out.length) {
        throw new Error("Failed to publish message");
      }
    },
    close(ws) {
      remainingClients++;
    },

    perMessageDeflate: false,
  },

  fetch(req, server) {
    if (
      server.upgrade(req, {
        data: {
          name:
            new URL(req.url).searchParams.get("name") ||
            "Client #" + (CLIENTS_TO_WAIT_FOR - remainingClients),
        },
      })
    )
      return;

    return new Response("Error");
  },
});

console.log(
  `Waiting for ${remainingClients} clients to connect...\n`,
  `  http://${server.hostname}:${port}/`
);