Skip to content

Latest commit

History

History
69 lines (49 loc) 路 1.96 KB

1.index.md

File metadata and controls

69 lines (49 loc) 路 1.96 KB
icon
ph:book-open-duotone

Getting Started

CrossWS provides a cross-platform API to define well-typed WebSocket apps that can then be integrated into various WebSocket servers using built-in adapters.

Writing a realtime WebSocket server that can work in different javascript and WebSocket runtimes is challenging because there is no single standard for WebSocket servers. You often need to go into many details of diffrent API implementations and it also makes switching from one runtime costly. CrossWS is a solution to this!

Important

CrossWS API is still under development and can change.

Quick Start

Tip

You can try CrossWS with online playground using unjs/h3 + unjs/listhen or alternatively integrate CrossWS with your own framework.

A simple WebSocket implementation looks like this:

// https://crossws.unjs.io/adapters
import wsAdapter from "crossws/adapters/<adapter>";

import { defineHooks } from "crossws";

const websocket = wsAdapter({
  hooks: {
    open(peer) {
      console.log("[ws] open", peer);
    },

    message(peer, message) {
      console.log("[ws] message", peer, message);
      if (message.text().includes("ping")) {
        peer.send("pong");
      }
    },

    close(peer, event) {
      console.log("[ws] close", peer, event);
    },

    error(peer, error) {
      console.log("[ws] error", peer, error);
    },
  },
});

::read-more{to="/guide/hooks" title="Hooks"} See Hooks for more usage details. ::

::read-more{to="/adapters" title="Adapters"} Hooks API is exactly same on all runtimes. See Adapters for integration details. ::

Using Package

You can install crossws from npm in your project:

:pm-install{name="crossws"}

Alternatively you can import it from CDN:

import { crossws } from "https://esm.sh/crossws";