Deno WebSocket Server πŸ”Œ

A WebSocket server library for Deno.

The raison d'Γͺtre for this library is to provide a unified async iterator for the events of all connected WebSocket clients. The way it does this is through a custom MuxAsyncInfiniteIterator (based on the MuxAsyncIterator), which multiplexes multiple async iterators into a single stream.

Note: This WebSocket server is not an EventEmitter (i.e. it does not use events with callbacks like websockets/ws). Instead, it specifies the asyncIterator symbol and should be used in conjunction with a for await...of loop, just like the Deno http server. The iterator yields WebSocketServerEvents which contain both the WebSocketEvent and the corresponding WebSocket from which the event was received.

Usage

Simple server

import { serve } from 'https://raw.githubusercontent.com/JohanWinther/websocket-server/master/mod.ts'
const server = serve(":8080");
for await (const { event } of server) {
  console.log(event);
}

Echo / broadcast server

Check out the example echo/broadcast server.

FAQ

How do I create a WebSocket client?

This library provides a class only for WebSocket servers, not WebSocket clients, because it is straightforward to create clients with the std/ws module.

Here is a simple example:

import { connectWebSocket } from "https://deno.land/std/ws/mod.ts";
try {
  const socket = await connectWebSocket("ws://127.0.0.1:8080");
  for await (const event of socket) {
    console.log(event);
    if (typeof event === "string" && event === "Who is this?") {
      socket.send("It is me, a simple WebSocket client.");
    }
  }
} catch (err) {
  console.error(`Could not connect to WebSocket: '${err}'`);
}

Changelog

GitHub releases is used for changelog entries.

License

MIT