aboutsummaryrefslogtreecommitdiff
path: root/bench/snippets/tcp-echo.node.mjs
blob: 336f9d5e2a118be1df668cb5bb832fe62b9db20f (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import { createRequire } from "node:module";
const net = createRequire(import.meta.url)("net");

const buffer = Buffer.from("Hello World!");
var counter = 0;
const handlers = {
  open() {
    if (!socket.data?.isServer) {
      if (!this.write(buffer)) {
        socket.data = { pending: buffer };
      }
    }
  },
  data(buffer) {
    if (!this.write(buffer)) {
      this.data = { pending: buffer.slice() };
      return;
    }
    counter++;
  },
  drain() {
    const pending = this.data?.pending;
    if (!pending) return;
    if (this.write(pending)) {
      this.data = undefined;
      counter++;
      return;
    }
  },
};

if (process.env.IS_SERVER) {
  if (net.createServer) {
    const server = net.createServer(function (socket) {
      socket.data = { isServer: true };
      socket.on("connection", handlers.open.bind(socket));
      socket.on("data", handlers.data.bind(socket));
      socket.on("drain", handlers.drain.bind(socket));
      socket.setEncoding("binary");
    });

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

    server.listen(8000);
  } else {
    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);

    const server = Bun.listen({
      socket: handlers,
      hostname: "0.0.0.0",
      port: 8000,
      data: {
        isServer: true,
      },
    });
  }
} else {
  const socket = net.connect({ host: "0.0.0.0", port: 8000 }, () => {});
  socket.on("connection", handlers.open.bind(socket));
  socket.on("data", handlers.data.bind(socket));
  socket.on("drain", handlers.drain.bind(socket));
  socket.setEncoding("binary");
  socket.write(buffer);
}