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智能索引记录
-
2026-02-28 05:05:31
教育培训
成功
标题:高一物理A1 第4期暑假补习补课辅导班-上海新王牌培优
简介:新王牌培优是上海好的初高中辅导培训机构,创立于2005年,采用分层授课,小班化教学的辅导补课方式 ,是一家致力于初高中辅
-
2026-02-27 17:18:43
综合导航
成功
标题:Photographing birds in the field
简介:1x.com is the world
-
2026-02-28 03:01:56
综合导航
成功
标题:ILSC Language Schools Services IELTS Test Centres
简介:Take the official IELTS test at ILSC Centres in Greater Vanc
-
2026-02-27 15:24:04
综合导航
成功
标题:Fecha DOT del neumático: qué indica realmente y cuándo deja de ser fiable
简介:La fecha DOT del neumático indica su antigüedad, pero no es
-
2026-02-27 14:32:52
金融理财
成功
标题:小赢理财代金券怎么用(小赢理财吧 百度贴吧)_火必 Huobi交易所
简介:本篇文章给大家谈谈小赢理财代金券怎么用,以及小赢理财吧 百度贴吧对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。
-
2026-02-28 05:23:45
综合导航
成功
标题:京东(JD.COM)-正品低价、品质保障、配送及时、轻松购物!
简介:京东JD.COM-专业的综合网上购物商城,为您提供正品低价的购物选择、优质便捷的服务体验。商品来自全球数十万品牌商家,囊
-
2026-02-27 19:25:44
教育培训
成功
标题:领导力学习数据赋能指南白皮书-果果圈模板
简介:领导力学习数据赋能指南白皮书,文档极其精美,内容丰富详细,欢迎学习使用。
-
2026-02-27 21:45:16
综合导航
成功
标题:ãããã¯ã¼ã¯æ©è½ã®è¨å®æ¹æ³ï¼Macintosh OS X 10.8ãå©ç¨ã®æ¹ï¼ ã¤ã³ã¿ã¼ãããæ¥ç¶è¨å® au
简介:ãããã¯ã¼ã¯æ©è½ã®è¨å®æ¹æ³ï¼Macintosh OS X 10.
-
2026-02-27 20:14:05
综合导航
成功
标题:Free Printable Autumn Coloring Page - Forest View with Animals EDU.COM
简介:Download our free printable autumn coloring page featuring a
-
2026-02-27 14:18:04
综合导航
成功
标题:Fun and Comfy Women's Printed Pajamas Aerie
简介:Sleep in style with Aerie
-
2026-02-28 00:12:30
新闻资讯
成功
标题:世界杯也走向“比拼”大数据的时代, 站长资讯平台
简介:《日本经济新闻》6月19日报道称,俄罗斯足球世界杯已于6月14日揭开战幕。作为第21次举办的足球世界杯,如何活用大数据有
-
2026-02-27 14:25:07
综合导航
成功
标题:Schaeffler Germany
简介:Schaeffler has been driving forward groundbreaking invention
-
2026-02-27 14:15:14
综合导航
成功
标题:Counter & Pop-up Display PIP - PIP Raleigh, NC
简介:Let PIP bring your dream to fruition with our counter and po
-
2026-02-28 01:46:17
综合导航
成功
标题:NVE Corp - Magnetic Switch Sensors
简介:This is Magnetic Switch Sensors.
-
2026-02-27 23:51:53
综合导航
成功
标题:人族鎮守使-第一千二百一十一章 鎮壓上古龍象最新章節-台灣小說網
简介:台灣小說網整理人族鎮守使全集無彈窗在線閱讀,當前章節:第一千二百一十一章 鎮壓上古龍象
-
2026-02-28 00:24:15
综合导航
成功
标题:Sporting News - NFL NBA MLB NCAA Boxing Soccer NASCAR
简介:The latest news, videos, scores and more on the biggest spor
-
2026-02-28 03:23:16
教育培训
成功
标题:高二物理A2寒假补习补课辅导班-上海新王牌培优
简介:新王牌培优是上海好的初高中辅导培训机构,创立于2005年,采用分层授课,小班化教学的辅导补课方式 ,是一家致力于初高中辅
-
2026-02-27 16:14:24
综合导航
成功
标题:An attempt to clarify what an embryo is
简介:What is really meant by the term ”human embryo” as used in A
-
2026-02-28 04:47:35
综合导航
成功
标题:Business Cards & Stationery PIP - PIP Anchorage, AK
简介:PIP can create you individual items or complete professional
-
2026-02-27 14:51:19
新闻资讯
成功
标题:法律法规_留学预科_大学留学预科_本科留学预科_国内重点大学留学预科_中外合作办学-中外合作办学教育信息网
简介:中外合作办学教育信息网,提供国内重点大学留学预科、本科留学预科、硕士留学预科等项目最新招生资讯。全国留学预科免费咨询热线
-
2026-02-28 00:52:15
综合导航
成功
标题:Ink Elbow Sleeve Funnel Neck Knit Cue
简介:Soft knit finish Semi relaxed fit Regular length Ribbed funn
-
2026-02-28 04:32:19
综合导航
成功
标题:Commercial property insurance FM
简介:FM delivers tailored commercial property insurance to protec
-
2026-02-27 21:29:41
综合导航
成功
标题:Gen-Z Influencer Freed from Abuse, Witchcraft, and Porn Addiction CBN
简介:Gen-Z social media influencer Yamilexis Fernandez broke the
-
2026-02-28 03:36:21
综合导航
成功
标题:Regalbediengerät
简介:Ein Regalbediengerät (RBG) ist ein Lagergerät, mit dem Ladee
-
2026-02-27 21:35:55
综合导航
成功
标题:News JSCL - Part 8JSCL Page 8
简介:JS Global Capital Initiative in London Attracts Global Inter
-
2026-02-27 21:25:44
综合导航
成功
标题:LPN - Long Term Care · GQR
简介:Long Term Care LPN Job Location: Canby, MN Profession: Licen
-
2026-02-28 04:41:37
综合导航
成功
标题:dmm6500 software 2 Tektronix
简介:Showcases selected features of the DMM6500.
-
2026-02-27 22:23:42
金融理财
成功
标题:银行理财表内表外(银行理财 表外)_火必 Huobi交易所
简介:本篇文章给大家谈谈银行理财表内表外,以及银行理财 表外对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。 本文目录一
-
2026-02-28 02:00:42
综合导航
成功
标题:产品中心 - 山东地六化学有限公司
简介:山东地六化学有限公司主要生产研发和销售醋酸、氯化铵、1.3反式、1,3-混合二氯丙烯系列(混合、乳化、反式)英文名:1,
-
2026-02-27 23:06:41
综合导航
成功
标题:2021年中共浙江省委党校研究生调剂复试安排-高顿教育
简介:为帮助大家应对研究生考试,这里为大家整理了2021年中共浙江省委党校研究生调剂复试安排的内容,供大家参考,更多考研简章,