Files
bun.sh/bench/snippets/tcp-echo.node.mjs
Jarred Sumner 02c920f4fd TCP & TLS Socket API (#1374)
* TCP Socket API

* Wip

* Add snippet for StringDecoder

* Rename `close` to `stop`, replace `close` with `end`

* Add a tcp echo server test

* Some docs

* Update README.md

* Fix build

* Update README.md

Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
2022-10-25 00:44:25 -07:00

53 lines
1.3 KiB
JavaScript

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;
}
},
};
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);
const socket = net.connect({ host: "localhost", 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);