aboutsummaryrefslogtreecommitdiff
path: root/bench/snippets/tcp-echo.bun.ts
blob: c0f227e75474e0540b5e80f89ac8cae83acc1273 (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
import { listen, connect } from "bun";

var counter = 0;
const msg = "Hello World!";

const handlers = {
  open(socket) {
    if (!socket.data?.isServer) {
      if (!socket.write(msg)) {
        socket.data = { pending: msg };
      }
    }
  },
  data(socket, buffer) {
    if (!socket.write(buffer)) {
      socket.data = { pending: buffer };
      return;
    }
    counter++;
  },
  drain(socket) {
    const pending = socket.data?.pending;
    if (!pending) return;
    if (socket.write(pending)) {
      socket.data = undefined;
      counter++;
      return;
    }
  },
};

setInterval(() => {
  console.log("Wrote", counter, "messages");
  counter = 0;
}, 1000);

if (process.env.IS_SERVER)
  listen({
    socket: handlers,
    hostname: "0.0.0.0",
    port: 8000,
    data: {
      isServer: true,
    },
  });
else
  await connect({
    socket: handlers,
    hostname: "localhost",
    port: 8000,
  });