search
HomeWeb Front-endJS TutorialWebSocket with JavaScript and Bun

Ensuring efficient and seamless communication between the client and server is key when building modern, real-time web applications. Traditional HTTP requests—like those used in polling—are stateless and one-directional. The client makes a request (e.g., using fetch or axios) to the server, and the server responds before the connection is closed. If the client needs fresh data, it must repeatedly send new requests at regular intervals, creating unnecessary latency and increasing load on both the client and server.

For example, if you're building a live chat app or a stock price tracker, polling would require the client to request updates every second or so, even when there’s no new data to fetch. This is where WebSockets shine.


The WebSocket approach

WebSockets provide a persistent, two-way communication channel between the client and the server. Once the connection is established, the server can instantly push updates to the client without waiting for a new request. This makes WebSockets ideal for scenarios where real-time updates are essential, such as:

  • Sending chat messages in a live chat application.
  • Broadcasting notifications or updates to multiple users simultaneously.
  • Streaming real-time data, such as stock prices, sports scores, or game states.

Using Vanilla JavaScript on the client side and the Bun runtime on the server side makes implementing WebSockets straightforward and efficient. For example:

  • The client can send a message to the server, and the server can instantly broadcast that message to other connected clients.
  • A persistent connection ensures no repetitive overhead of re-establishing connections, unlike polling.

In this scenario, WebSockets offer lower latency, reduced server load, and a smoother user experience than traditional polling methods.


Building a WebSocket project

Step 1: setting up a Bun Project

First, ensure the Bun is installed. Then create a new Bun project, create a new empty directory, enter into the new directory, and initialize the project via the bun init command:

mkdir websocket-demo
cd websocket-demo
bun init

The bun init command will create the package.json file, a "hello world" index.ts file, the .gitignore file, the tsconfig.json file for the typescript configuration, and a README.md file.

Now, you can start creating your JavaScript code. I'm going to show you the whole script; then we will explore all the relevant parts. You can edit the index.ts file:

console.log("? Hello via Bun! ?");
const server = Bun.serve({
  port: 8080, // defaults to $BUN_PORT, $PORT, $NODE_PORT otherwise 3000
  fetch(req, server) {
    const url = new URL(req.url);
    if (url.pathname === "/") return new Response(Bun.file("./index.html"));
    if (url.pathname === "/surprise") return new Response("?");

    if (url.pathname === "/chat") {
      if (server.upgrade(req)) {
        return; // do not return a Response
      }
      return new Response("Upgrade failed", { status: 400 });
    }

    return new Response("404!");
  },
  websocket: {
    message(ws, message) {
      console.log("✉️ A new Websocket Message is received: " + message);
      ws.send("✉️ I received a message from you:  " + message);
    }, // a message is received
    open(ws) {
      console.log("? A new Websocket Connection");
      ws.send("? Welcome baby");
    }, // a socket is opened
    close(ws, code, message) {
      console.log("⏹️ A Websocket Connection is CLOSED");
    }, // a socket is closed
    drain(ws) {
      console.log("DRAIN EVENT");
    }, // the socket is ready to receive more data
  },
});
console.log(`? Server (HTTP and WebSocket) is launched ${server.url.origin}`);

Documenting the code for a basic WebSocket server using Bun

Below is a breakdown of the provided code, explaining each part and its functionality.


Server Initialization

mkdir websocket-demo
cd websocket-demo
bun init

The Bun.serve method initializes a server capable of handling both HTTP and WebSocket requests.

  • port: 8080: Specifies the port on which the server listens. Defaults to common environment variables or 3000 if unspecified. In this example the port is hardcoded to 8080. If you want to provide a more flexible way, you should remove the port line and allow to Bun to manage the port. So you can run the script via export BUN_PORT=4321; bun run index.ts

HTTP request handling

console.log("? Hello via Bun! ?");
const server = Bun.serve({
  port: 8080, // defaults to $BUN_PORT, $PORT, $NODE_PORT otherwise 3000
  fetch(req, server) {
    const url = new URL(req.url);
    if (url.pathname === "/") return new Response(Bun.file("./index.html"));
    if (url.pathname === "/surprise") return new Response("?");

    if (url.pathname === "/chat") {
      if (server.upgrade(req)) {
        return; // do not return a Response
      }
      return new Response("Upgrade failed", { status: 400 });
    }

    return new Response("404!");
  },
  websocket: {
    message(ws, message) {
      console.log("✉️ A new Websocket Message is received: " + message);
      ws.send("✉️ I received a message from you:  " + message);
    }, // a message is received
    open(ws) {
      console.log("? A new Websocket Connection");
      ws.send("? Welcome baby");
    }, // a socket is opened
    close(ws, code, message) {
      console.log("⏹️ A Websocket Connection is CLOSED");
    }, // a socket is closed
    drain(ws) {
      console.log("DRAIN EVENT");
    }, // the socket is ready to receive more data
  },
});
console.log(`? Server (HTTP and WebSocket) is launched ${server.url.origin}`);

  • fetch(req, server): Handles incoming HTTP requests.
  • Root path /: serves the index.html file.
  • /surprise path: returns a fun surprise emoji response ?.
  • /chat Path: Tries to "upgrade" the connection to a WebSocket connection. If the upgrade fails, it returns an error 400 response.

WebSocket handlers

The websocket key defines event handlers to manage WebSocket connections.

? Connection Open (open)

const server = Bun.serve({
  port: 8080, // defaults to $BUN_PORT, $PORT, $NODE_PORT otherwise 3000
  ...
});

Triggered when a client establishes a WebSocket connection.

  • ws.send(...): sends a welcome message to the client who requested the connection..

✉️ Receiving a Message (message)

fetch(req, server) {
  const url = new URL(req.url);

  if (url.pathname === "/") 
    return new Response(Bun.file("./index.html"));

  if (url.pathname === "/surprise") 
    return new Response("?");

  if (url.pathname === "/chat") {
    if (server.upgrade(req)) {
      return; // do not return a Response
    }
    return new Response("Upgrade failed", { status: 400 });
  }

  return new Response("404!");
}

Triggered when the server receives a message from the client.

  • ws.send(...): echoes back the received message with a confirmation.

⏹️ Connection Close (close)

open(ws) {
  console.log("? A new Websocket Connection");
  ws.send("? Welcome baby");
}

Triggered when a WebSocket connection is closed.

Parameters:

  • code: reason code for closing the connection.
  • message: additional details about the closure.

? Drain Event (drain)

message(ws, message) {
  console.log("✉️ A new Websocket Message is received: " + message);
  ws.send("✉️ I received a message from you: " + message);
}

The drain event is triggered when the WebSocket is ready to accept more data after being temporarily overwhelmed.


Log the server launch

close(ws, code, message) {
  console.log("⏹️ A Websocket Connection is CLOSED");
}

Logs the server's URL to the console once it's running.


Recap about how it works

  1. HTTP Requests: handles standard HTTP requests (e.g., serving a file or responding with a status).
  2. WebSocket Upgrade: upgrades HTTP connections to WebSocket connections when clients connect to /chat.
  3. Real-Time Communication: handles persistent communication between the server and clients using WebSocket events (open, message, close, drain).

Running the server

Once you have your index.ts file, you can start the server via bun run:

drain(ws) {
  console.log("DRAIN EVENT");
}

The server is ready and up and running. Now, we can implement the client.

WebSocket with JavaScript and Bun

Next steps

Now we understand the structure of the script for handling the WebSocket, the next steps are:

  • implementing the HTML for the WebSocket client;
  • Implementing broadcasting logic to forward messages from one client to all connected clients.

The above is the detailed content of WebSocket with JavaScript and Bun. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools