Skip to main content
Deno 2 is finally here 🎉️
Learn more
Module

x/ayonli_jsext/esm/ws.js>WebSocketServer

A JavaScript extension package for building strong and modern applications.
Latest
class WebSocketServer
import { WebSocketServer } from "https://deno.land/x/ayonli_jsext@v0.9.72/esm/ws.js";

A unified WebSocket server interface for Node.js, Deno, Bun and Cloudflare Workers.

There are two ways to handle WebSocket connections:

  1. By passing a listener function to the constructor, handle all connections in a central place.
  2. By using the socket object returned from the upgrade method to handle each connection in a more flexible way. However, at this stage, the connection may not be ready yet, and we need to listen the open event or wait for the ready promise (deprecated) to resolve before we can start sending messages.

The socket object is an async iterable object, which can be used in the for await...of loop to read messages with backpressure support.

Examples

Example 1

// centralized connection handler
import { WebSocketServer } from "@ayonli/jsext/ws";

const wsServer = new WebSocketServer(socket => {
    console.log("WebSocket connection established.");

    socket.addEventListener("message", (event) => {
        socket.send("received: " + event.data);
    });

    socket.addEventListener("error", (event) => {
        console.error("WebSocket connection error:", event.error);
    });

    socket.addEventListener("close", (event) => {
        console.log(`WebSocket connection closed, reason: ${event.reason}, code: ${event.code}`);
    });
});

// Node.js
import * as http from "node:http";
const httpServer = http.createServer(req => {
     wsServer.upgrade(req);
});
httpServer.listen(3000);

// Node.js (withWeb)
import { withWeb } from "@ayonli/jsext/http";
const httpServer2 = http.createServer(withWeb(req => {
     const { response } = wsServer.upgrade(req);
     return response;
}));
httpServer2.listen(3001);

// Bun
const bunServer = Bun.serve({
    fetch(req) {
        const { response } = wsServer.upgrade(req);
        return response;
    },
    websocket: wsServer.bunListener,
});
wsServer.bunBind(bunServer);

// Deno
Deno.serve(req => {
    const { response } = wsServer.upgrade(req);
    return response;
});

// Cloudflare Workers
export default {
    fetch(req) {
        const { response } = wsServer.upgrade(req);
        return response;
    },
};

Example 2

// per-request connection handler (Deno example)
import { WebSocketServer } from "@ayonli/jsext/ws";

const wsServer = new WebSocketServer();

Deno.serve(req => {
    const { socket, response } = wsServer.upgrade(req);

    socket.addEventListener("open", () => {
        console.log("WebSocket connection established.");
    });

    socket.addEventListener("message", (event) => {
        socket.send("received: " + event.data);
    });

    socket.addEventListener("error", (event) => {
        console.error("WebSocket connection error:", event.error);
    });

    socket.addEventListener("close", (event) => {
        console.log(`WebSocket connection closed, reason: ${event.reason}, code: ${event.code}`);
    });

    // The response should be returned immediately, otherwise the web socket
    // will not be ready.
    return response;
});

Example 3

// async iterable
const wsServer = new WebSocketServer(async socket => {
    console.log("WebSocket connection established.");

    try {
        for await (const message of socket) {
            socket.send("received: " + message);
        }
    } catch (error) {
        console.error("WebSocket connection error:", error);
    }

    console.log("WebSocket connection closed");
});

Deno.serve(req => {
    const { response } = wsServer.upgrade(req);
    return response;
});

Constructors

new
WebSocketServer(...args)

Properties

readonly
bunListener

A WebSocket listener for Bun.serve().

readonly
clients

An iterator that yields all connected WebSocket clients, can be used to broadcast messages to all clients.

Methods

bunBind(server)

Used in Bun, to bind the WebSocket server to the Bun server instance.

upgrade(request)