温馨提示:本站仅提供公开网络链接索引服务,不存储、不篡改任何第三方内容,所有内容版权归原作者所有
AI智能索引来源:http://www.bun.com/docs/runtime/networking/tcp
点击访问原文链接
TCP - BunSkip to main contentBun home pageSearch...⌘KInstall BunSearch...NavigationNetworkingTCPRuntimePackage ManagerBundlerTest RunnerGuidesReferenceBlogFeedbackdiv:first-child]:!hidden peer-[.is-custom]:[&>div:first-child]:sm:!hidden peer-[.is-custom]:[&>div:first-child]:md:!hidden peer-[.is-custom]:[&>div:first-child]:lg:!hidden peer-[.is-custom]:[&>div:first-child]:xl:!hidden">Get StartedWelcome to BunInstallationQuickstartTypeScriptbun initbun createCore RuntimeBun RuntimeWatch ModeDebuggingREPLbunfig.tomlFile & Module SystemFile TypesModule ResolutionJSXAuto-installPluginsFile System RouterHTTP serverServerRoutingCookiesTLSError HandlingMetricsNetworkingFetchWebSocketsTCPUDPDNSData & StorageCookiesFile I/OStreamsBinary DataArchiveSQLSQLiteS3RedisConcurrencyWorkersProcess & SystemEnvironment VariablesShellSpawnInterop & ToolingNode-APIFFIC CompilerTranspilerUtilitiesSecretsConsoleYAMLMarkdownJSON5JSONLHTMLRewriterHashingGlobSemverColorUtilsStandards & CompatibilityGlobalsBun APIsWeb APIsNode.js CompatibilityContributingRoadmapBenchmarkingContributingBuilding WindowsBindgenLicenseOn this pageStart a server (Bun.listen())Create a connection (Bun.connect())Hot reloadingBufferingNetworkingTCPCopy pagespan]:line-clamp-1 overflow-hidden group flex items-center py-0.5 gap-1 text-sm text-gray-950/50 dark:text-white/50 group-hover:text-gray-950/70 dark:group-hover:text-white/70 rounded-none rounded-r-xl border px-3 border-gray-200 aspect-square dark:border-white/[0.07] bg-background-light dark:bg-background-dark hover:bg-gray-600/5 dark:hover:bg-gray-200/5" aria-label="More actions" type="button" id="radix-_R_2shjinpfd9rqaabsnpfdb_" aria-haspopup="menu" aria-expanded="false" data-state="closed">*]:[overflow-wrap:anywhere]">Use Bun’s native TCP API to implement performance sensitive systems like database clients, game servers, or anything that needs to communicate over TCP (instead of HTTP)

Copy pagespan]:line-clamp-1 overflow-hidden group flex items-center py-0.5 gap-1 text-sm text-gray-950/50 dark:text-white/50 group-hover:text-gray-950/70 dark:group-hover:text-white/70 rounded-none rounded-r-xl border px-3 border-gray-200 aspect-square dark:border-white/[0.07] bg-background-light dark:bg-background-dark hover:bg-gray-600/5 dark:hover:bg-gray-200/5" aria-label="More actions" type="button" id="radix-_R_5hjinpfd9rqaabsnpfdb_" aria-haspopup="menu" aria-expanded="false" data-state="closed">This is a low-level API intended for library authors and for advanced use cases. ​Start a server (Bun.listen()) To start a TCP server with Bun.listen: server.tsCopyBun.listen({ hostname: "localhost", port: 8080, socket: { data(socket, data) {}, // message received from client open(socket) {}, // socket opened close(socket, error) {}, // socket closed drain(socket) {}, // socket ready for more data error(socket, error) {}, // error handler }, });

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.server.tsCopyBun.listen({ hostname: "localhost", port: 8080, socket: { open(socket) {}, data(socket, data) {}, drain(socket) {}, close(socket, error) {}, 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. Contextual data can be attached to a socket in the open handler. server.tsCopytype SocketData = { sessionId: string }; Bun.listenSocketData>({ 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 key and cert fields. server.tsCopyBun.listen({ hostname: "localhost", port: 8080, socket: { data(socket, data) {}, }, tls: { // can be string, BunFile, TypedArray, Buffer, or array thereof key: Bun.file("./key.pem"), cert: Bun.file("./cert.pem"), }, }); The key and cert fields expect the contents of your TLS key and certificate. This can be a string, BunFile, TypedArray, or Buffer. server.tsCopyBun.listen({ // ... tls: { key: Bun.file("./key.pem"), // BunFile key: fs.readFileSync("./key.pem"), // Buffer key: fs.readFileSync("./key.pem", "utf8"), // string key: [Bun.file("./key1.pem"), Bun.file("./key2.pem")], // array of above }, }); The result of Bun.listen is a server that conforms to the TCPSocket interface. server.tsCopyconst 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 (Bun.connect()) 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. server.tsCopy// The client const socket = await Bun.connect({ hostname: "localhost", port: 8080, socket: { data(socket, data) {}, open(socket) {}, close(socket, error) {}, 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. Copy// The client const socket = await Bun.connect({ // ... config tls: true, }); ​Hot reloading Both TCP servers and sockets can be hot reloaded with new handlers. server.tsclient.tsCopyconst server = Bun.listen({ /* config */ }); // reloads handlers for all active server-side sockets server.reload({ socket: { data() { // new 'data' handler }, }, }); ​Buffering Currently, TCP sockets in Bun do not buffer data. For performance-sensitive code, it’s important to consider buffering carefully. For example, this: Copysocket.write("h"); socket.write("e"); socket.write("l"); socket.write("l"); socket.write("o"); …performs significantly worse than this: Copysocket.write("hello"); To simplify this for now, consider using Bun’s ArrayBufferSink with the {stream: true} option: server.tsCopyimport { ArrayBufferSink } from "bun"; const sink = new ArrayBufferSink(); sink.start({ stream: true, highWaterMark: 1024, }); sink.write("h"); sink.write("e"); sink.write("l"); sink.write("l"); sink.write("o"); queueMicrotask(() => { const data = sink.flush(); const wrote = socket.write(data); if (wrote data.byteLength) { // put it back in the sink if the socket is full sink.write(data.subarray(wrote)); } }); CorkingSupport for corking is planned, but in the meantime backpressure must be managed manually with the drain handler.

Was this page helpful?

YesNoSuggest editsRaise issueWebSocketsPreviousUDPNext⌘IxgithubdiscordyoutubePowered by

智能索引记录