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
const server = Bun.serve({
port: 8080, // defaults to $BUN_PORT, $PORT, $NODE_PORT otherwise 3000
...
});
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 or3000
if unspecified. In this example the port is hardcoded to 8080. If you want to provide a more flexible way, you should remove theport
line and allow to Bun to manage the port. So you can run the script viaexport BUN_PORT=4321; bun run index.ts
HTTP request handling
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!");
}
-
fetch(req, server)
: Handles incoming HTTP requests. - Root path
/
: serves theindex.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 error400
response.
WebSocket handlers
The websocket
key defines event handlers to manage WebSocket connections.
👋 Connection Open (open
)
open(ws) {
console.log("👋 A new Websocket Connection");
ws.send("👋 Welcome baby");
}
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
)
message(ws, message) {
console.log("✉️ A new Websocket Message is received: " + message);
ws.send("✉️ I received a message from you: " + message);
}
Triggered when the server receives a message from the client.
-
ws.send(...)
: echoes back the received message with a confirmation.
⏹️ Connection Close (close
)
close(ws, code, message) {
console.log("⏹️ A Websocket Connection is CLOSED");
}
Triggered when a WebSocket connection is closed.
Parameters:
-
code
: reason code for closing the connection. -
message
: additional details about the closure.
😅 Drain Event (drain
)
drain(ws) {
console.log("DRAIN EVENT");
}
The drain event is triggered when the WebSocket is ready to accept more data after being temporarily overwhelmed.
Log the server launch
console.log(`🚀 Server (HTTP and WebSocket) is launched ${server.url.origin}`);
Logs the server's URL to the console once it's running.
Recap about how it works
- HTTP Requests: handles standard HTTP requests (e.g., serving a file or responding with a status).
- WebSocket Upgrade: upgrades HTTP connections to WebSocket connections when clients connect to
/chat
. - 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
:
bun run index.ts
The server is ready and up and running. Now, we can implement the client.
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. 🔗 Go to article.
- Implementing broadcasting logic to forward messages from one client to all connected clients.
Top comments (0)