Skip to content

WebSockets

BrewedSys edited this page Mar 30, 2026 · 1 revision

WebSockets

Http-native supports WebSocket connections through a Rust-backed upgrade mechanism.

Basic Usage

import { createApp } from "@http-native/core";

const app = createApp();

app.ws("/chat", (ws) => {
  console.log("Client connected");

  ws.on("message", (data) => {
    console.log("Received:", data);
    ws.send(`Echo: ${data}`);
  });

  ws.on("close", () => {
    console.log("Client disconnected");
  });
});

await app.listen({ port: 8190 });

How It Works

  1. The client sends an HTTP upgrade request to the WebSocket path
  2. The Rust layer handles the WebSocket handshake natively
  3. Once upgraded, frames are parsed and dispatched to your JavaScript handler
  4. Messages are sent back through the Rust layer for efficient socket writes

Events

Event Callback Description
message (data) => void Received a message from the client
close () => void Connection was closed
error (err) => void An error occurred

Methods

Method Description
ws.send(data) Send a message to the client
ws.close() Close the connection

Example: Chat Room

const clients = new Set();

app.ws("/chat", (ws) => {
  clients.add(ws);

  ws.on("message", (msg) => {
    for (const client of clients) {
      if (client !== ws) client.send(msg);
    }
  });

  ws.on("close", () => {
    clients.delete(ws);
  });
});

Client-Side

const ws = new WebSocket("ws://localhost:8190/chat");

ws.onopen = () => ws.send("Hello!");
ws.onmessage = (event) => console.log("Server says:", event.data);

Clone this wiki locally