aboutsummaryrefslogtreecommitdiff
path: root/docs/api/tcp.md
diff options
context:
space:
mode:
Diffstat (limited to 'docs/api/tcp.md')
-rw-r--r--docs/api/tcp.md198
1 files changed, 198 insertions, 0 deletions
diff --git a/docs/api/tcp.md b/docs/api/tcp.md
new file mode 100644
index 000000000..5e04dd348
--- /dev/null
+++ b/docs/api/tcp.md
@@ -0,0 +1,198 @@
+Use Bun's native TCP API implement performance sensitive systems like database clients, game servers, or anything that needs to communicate over TCP (instead of HTTP). This is a low-level API intended for library authors and for advanced use cases.
+
+## Start a server
+
+To start a TCP server with `Bun.listen`:
+
+```ts
+Bun.listen({
+ hostname: "localhost",
+ port: 8080,
+ socket: {
+ data(socket, data) {}, // message received from client
+ open(socket) {}, // socket opened
+ close(socket) {}, // socket closed
+ drain(socket) {}, // socket ready for more data
+ error(socket, error) {}, // error handler
+ },
+});
+```
+
+{% details summary="An API designed for speed" %}
+
+In Bun, a set of handlers are declared once per server instead of assigning callbacks to each socket, as with Node.js `EventEmitters` or the web-standard `WebSocket` API.
+
+```ts
+Bun.listen({
+ hostname: "localhost",
+ port: 8080,
+ socket: {
+ open(socket) {},
+ data(socket, data) {},
+ drain(socket) {},
+ close(socket) {},
+ error(socket, error) {},
+ },
+});
+```
+
+For performance-sensitive servers, assigning listeners to each socket can cause significant garbage collector pressure and increase memory usage. By contrast, Bun only allocates one handler function for each event and shares it among all sockets. This is a small optimization, but it adds up.
+
+{% /details %}
+
+Contextual data can be attached to a socket in the `open` handler.
+
+```ts
+type SocketData = { sessionId: string };
+
+Bun.listen<SocketData>({
+ hostname: "localhost",
+ port: 8080,
+ socket: {
+ data(socket, data) {
+ socket.write(`${socket.data.sessionId}: ack`);
+ },
+ open(socket) {
+ socket.data = { sessionId: "abcd" };
+ },
+ },
+});
+```
+
+To enable TLS, pass a `tls` object containing `keyFile` and `certFile` properties.
+
+```ts
+Bun.listen({
+ hostname: "localhost",
+ port: 8080,
+ socket: {
+ data(socket, data) {},
+ },
+ tls: {
+ certFile: "cert.pem",
+ keyFile: "key.pem",
+ },
+});
+```
+
+The result of `Bun.listen` is a server that conforms to the `TCPSocket` instance.
+
+```ts
+const server = Bun.listen({
+ /* config*/
+});
+
+// stop listening
+// parameter determines whether active connections are closed
+server.stop(true);
+
+// let Bun process exit even if server is still listening
+server.unref();
+```
+
+## Create a connection
+
+Use `Bun.connect` to connect to a TCP server. Specify the server to connect to with `hostname` and `port`. TCP clients can define the same set of handlers as `Bun.listen`, plus a couple client-specific handlers.
+
+```ts
+// The client
+const socket = Bun.connect({
+ hostname: "localhost",
+ port: 8080,
+
+ socket: {
+ data(socket, data) {},
+ open(socket) {},
+ close(socket) {},
+ drain(socket) {},
+ error(socket, error) {},
+
+ // client-specific handlers
+ connectError(socket, error) {}, // connection failed
+ end(socket) {}, // connection closed by server
+ timeout(socket) {}, // connection timed out
+ },
+});
+```
+
+To require TLS, specify `tls: true`.
+
+```ts
+// The client
+const socket = Bun.connect({
+ // ... config
+ tls: true,
+});
+```
+
+## Hot reloading
+
+Both TCP servers and sockets can be hot reloaded with new handlers.
+
+{% codetabs %}
+
+```ts#Server
+const server = Bun.listen({ /* config */ })
+
+// reloads handlers for all active server-side sockets
+server.reload({
+ socket:
+ data(){
+ // new 'data' handler
+ }
+ }
+})
+```
+
+```ts#Client
+const socket = Bun.connect({ /* config */ })
+socket.reload({
+ data(){
+ // new 'data' handler
+ }
+})
+```
+
+{% /codetabs %}
+
+## Buffering
+
+Currently, TCP sockets in Bun do not buffer data. For performance-sensitive code, it's important to consider buffering carefully. For example, this:
+
+```ts
+socket.write("h");
+socket.write("e");
+socket.write("l");
+socket.write("l");
+socket.write("o");
+```
+
+...performs significantly worse than this:
+
+```ts
+socket.write("hello");
+```
+
+To simplify this for now, consider using Bun's `ArrayBufferSink` with the `{stream: true}` option:
+
+```ts
+const sink = new ArrayBufferSink({ stream: true, highWaterMark: 1024 });
+
+sink.write("h");
+sink.write("e");
+sink.write("l");
+sink.write("l");
+sink.write("o");
+
+queueMicrotask(() => {
+ var data = sink.flush();
+ if (!socket.write(data)) {
+ // put it back in the sink if the socket is full
+ sink.write(data);
+ }
+});
+```
+
+{% callout %}
+**Corking** — Support for corking is planned, but in the meantime backpressure must be managed manually with the `drain` handler.
+{% /callout %}
/> hiroki osame 1-1/+5 2023-04-05rebase (#1501)Gravatar dave caruso 2-144/+305 2023-04-05Update `typecheck` (#2572)Gravatar Colin McDonnell 3-4/+8 2023-04-05prependGravatar Jarred Sumner 1-7/+3 2023-04-05Add tests for `bun test` with preload scripts (#2566)Gravatar Jake Boone 2-1/+107 2023-04-05Disable buffering when we clear terminalGravatar Jarred Sumner 1-0/+2 2023-04-05PrettierGravatar Jarred Sumner 3-4/+4 2023-04-05fix(fetch.proxy) fix proxy authentication (#2554)Gravatar Ciro Spaciari 3-31/+186 2023-04-05fix: build warnings (#2562)Gravatar hiroki osame 4-4/+1 2023-04-05In Documentation, move --watch before the script name (#2569)Gravatar Lawlzer 1-4/+5 2023-04-05fix `deepEquals` with array holes and accessors (#2557)Gravatar Dylan Conway 2-10/+249 2023-04-05fix: modules to have null prototype (#2561)Gravatar hiroki osame 2-2/+9 2023-04-04:clock1: :clock2: :clock3:Gravatar Jarred Sumner 1-1/+1 2023-04-04Implement `import.meta.main` (#2556)Gravatar Jarred Sumner 10-8/+89 2023-04-04Dylan/fix some failing tests (#2544)Gravatar Jarred Sumner 10-29/+72 2023-04-04Add npm benchmark (#2555)Gravatar Colin McDonnell 13-1/+271 2023-04-03Use absolute paths morebun-v0.5.9Gravatar Jarred Sumner 2-6/+11 2023-04-03Fix test failureGravatar Jarred Sumner 1-15/+18