本文档涵盖了 Bun 的 HTTP 服务器和网络基础设施,包括通过 Bun.serve() 提供的高性能 HTTP/WebSocket 服务器、fetch() 使用的 HTTP 客户端以及底层网络层。有关 CLI 内置开发服务器的信息,请参阅 CLI Architecture。
Bun 的网络堆栈基于 µWebSockets (uWS) 构建,提供支持 WebSocket 的服务器和客户端 HTTP 功能。其架构从高级 JavaScript API 延伸到低级套接字管理。
Sources: src/bun.js/api/server.zig423-447 src/http.zig21-52 src/deps/uws.zig1-30
The Bun.serve() API uses a generic server implementation that supports both HTTP and HTTPS configurations to create high-performance HTTP/WebSocket servers.
Sources: src/bun.js/api/server.zig423-447 src/bun.js/api/server.zig189-191 src/bun.js/api/server.zig67-186
The server processes incoming requests through a multi-stage pipeline with support for static files, dynamic routes, and WebSocket upgrades.
Sources: src/bun.js/api/server.zig445-456 src/bun.js/api/server.zig495-503 src/bun.js/api/server.zig63-64
| 组件 | 目的 | 关键类型 |
|---|---|---|
NewServer() | Generic server factory | ThisServer, RequestContext |
ServerConfig | Server configuration | Routes, WebSocket, TLS settings |
AnyRoute | Route abstraction | .static, .html, .framework_router |
RequestContext | Per-request state | Headers, body, response data |
WebSocket functionality is tightly integrated with the HTTP server, allowing seamless upgrades from HTTP connections.
Sources: src/bun.js/api/server.zig657-921 src/bun.js/api/server.zig48-49 src/bun.js/api/server.zig610-655
Bun's HTTP client implementation powers the fetch() API and handles HTTP/HTTPS requests with support for streaming, redirects, and various authentication methods.
Sources: src/http.zig115-146 src/http.zig148-219 src/http.zig42-50
| Body 类型 | 描述 | 用例 |
|---|---|---|
bytes | In-memory byte array | Small requests, JSON data |
sendfile | Zero-copy file transmission | Large file uploads |
流 | Streaming buffer | Real-time data, chunked uploads |
The networking foundation uses µWebSockets bindings and provides socket APIs for direct network programming.
Sources: src/bun.js/api/bun/socket.zig305-478 src/bun.js/api/bun/socket.zig113-303 src/deps/uws.zig1-150
Sources: src/bun.js/api/bun/socket.zig23-94 src/bun.js/api/bun/socket.zig345-364 src/http.zig30-33
Bun's networking layer is optimized for high throughput with features like corking, automatic flushing, and zero-copy operations where possible.
| 组件 | 目的 | 主要功能 |
|---|---|---|
StreamBuffer | Buffered I/O operations | Backpressure handling, chunked transfer |
HTTPServerWritable | Server response streaming | Auto-flushing, memory management |
Sendfile | Zero-copy file transmission | Direct kernel operations on Linux |
AutoFlusher | Automatic write flushing | Reduces syscall overhead |
Sources: src/bun.js/webcore/streams.zig679-1083 src/http.zig148-219 src/bun.js/webcore/streams.zig594-677