菜单

HTTP 服务器和网络

相关源文件

本文档涵盖了 Bun 的 HTTP 服务器和网络基础设施,包括通过 Bun.serve() 提供的​​高性能 HTTP/WebSocket 服务器、fetch() 使用的 HTTP 客户端以及底层网络层。有关 CLI 内置开发服务器的信息,请参阅 CLI Architecture

架构概述

Bun 的网络堆栈基于 µWebSockets (uWS) 构建,提供支持 WebSocket 的服务器和客户端 HTTP 功能。其架构从高级 JavaScript API 延伸到低级套接字管理。

Core Networking Stack

Sources: src/bun.js/api/server.zig423-447 src/http.zig21-52 src/deps/uws.zig1-30

Server API (Bun.serve)

The Bun.serve() API uses a generic server implementation that supports both HTTP and HTTPS configurations to create high-performance HTTP/WebSocket servers.

Server Creation and Configuration

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 factoryThisServer, RequestContext
ServerConfigServer configurationRoutes, WebSocket, TLS settings
AnyRouteRoute abstraction.static, .html, .framework_router
RequestContextPer-request stateHeaders, body, response data

WebSocket Support

WebSocket functionality is tightly integrated with the HTTP server, allowing seamless upgrades from HTTP connections.

WebSocket Upgrade Process

Sources: src/bun.js/api/server.zig657-921 src/bun.js/api/server.zig48-49 src/bun.js/api/server.zig610-655

HTTP Client and Fetch

Bun's HTTP client implementation powers the fetch() API and handles HTTP/HTTPS requests with support for streaming, redirects, and various authentication methods.

HTTP 客户端架构

Sources: src/http.zig115-146 src/http.zig148-219 src/http.zig42-50

Request Body Handling

Body 类型描述用例
bytesIn-memory byte arraySmall requests, JSON data
sendfileZero-copy file transmissionLarge file uploads
Streaming bufferReal-time data, chunked uploads

Low-Level Networking

The networking foundation uses µWebSockets bindings and provides socket APIs for direct network programming.

Socket API Structure

Sources: src/bun.js/api/bun/socket.zig305-478 src/bun.js/api/bun/socket.zig113-303 src/deps/uws.zig1-150

TLS and SSL Configuration

Sources: src/bun.js/api/bun/socket.zig23-94 src/bun.js/api/bun/socket.zig345-364 src/http.zig30-33

Performance and Streaming

Bun's networking layer is optimized for high throughput with features like corking, automatic flushing, and zero-copy operations where possible.

流式实现

组件目的主要功能
StreamBufferBuffered I/O operationsBackpressure handling, chunked transfer
HTTPServerWritableServer response streamingAuto-flushing, memory management
SendfileZero-copy file transmissionDirect kernel operations on Linux
AutoFlusherAutomatic write flushingReduces syscall overhead

Sources: src/bun.js/webcore/streams.zig679-1083 src/http.zig148-219 src/bun.js/webcore/streams.zig594-677