forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcp.ts
49 lines (45 loc) · 906 Bytes
/
tcp.ts
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
import { listen, connect } from "bun";
var counter = 0;
const msg = Buffer.from("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);
const server = listen({
socket: handlers,
hostname: "localhost",
port: 8080,
data: {
isServer: true,
},
});
const connection = await connect({
socket: handlers,
hostname: "localhost",
port: 8080,
});