1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-12-23 07:44:48 -05:00
denoland-deno/std/ws
2020-12-06 09:51:13 -05:00
..
example_server.ts doc: Improved ws example and README (#5636) 2020-06-04 15:13:33 -04:00
example_test.ts chore: add copyright (#7593) 2020-09-21 08:26:41 -04:00
mod.ts feat(std/ws): protocol & version support (#8505) 2020-11-26 16:38:15 +01:00
README.md docs(std): version all imports in README (#7442) 2020-10-04 14:18:36 +02:00
test.ts BREAKING(std/bytes): Adjust APIs based on std-wg discussion (#8612) 2020-12-06 09:51:13 -05:00

ws

ws module is made to provide helpers to create WebSocket server. For client WebSockets, use the WebSocket API.

Usage

// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { serve } from "https://deno.land/std@$STD_VERSION/http/server.ts";
import {
  acceptWebSocket,
  isWebSocketCloseEvent,
  isWebSocketPingEvent,
  WebSocket,
} from "https://deno.land/std@$STD_VERSION/ws/mod.ts";

async function handleWs(sock: WebSocket) {
  console.log("socket connected!");
  try {
    for await (const ev of sock) {
      if (typeof ev === "string") {
        // text message.
        console.log("ws:Text", ev);
        await sock.send(ev);
      } else if (ev instanceof Uint8Array) {
        // binary message.
        console.log("ws:Binary", ev);
      } else if (isWebSocketPingEvent(ev)) {
        const [, body] = ev;
        // ping.
        console.log("ws:Ping", body);
      } else if (isWebSocketCloseEvent(ev)) {
        // close.
        const { code, reason } = ev;
        console.log("ws:Close", code, reason);
      }
    }
  } catch (err) {
    console.error(`failed to receive frame: ${err}`);

    if (!sock.isClosed) {
      await sock.close(1000).catch(console.error);
    }
  }
}

if (import.meta.main) {
  /** websocket echo server */
  const port = Deno.args[0] || "8080";
  console.log(`websocket server is running on :${port}`);
  for await (const req of serve(`:${port}`)) {
    const { conn, r: bufReader, w: bufWriter, headers } = req;
    acceptWebSocket({
      conn,
      bufReader,
      bufWriter,
      headers,
    })
      .then(handleWs)
      .catch(async (err) => {
        console.error(`failed to accept websocket: ${err}`);
        await req.respond({ status: 400 });
      });
  }
}

API

isWebSocketCloseEvent

Returns true if input value is a WebSocketCloseEvent, false otherwise.

isWebSocketPingEvent

Returns true if input value is a WebSocketPingEvent, false otherwise.

isWebSocketPongEvent

Returns true if input value is a WebSocketPongEvent, false otherwise.

unmask

Unmask masked WebSocket payload.

writeFrame

Write WebSocket frame to inputted writer.

readFrame

Read WebSocket frame from inputted BufReader.

createMask

Create mask from the client to the server with random 32bit number.

acceptable

Returns true if input headers are usable for WebSocket, otherwise false.

createSecAccept

Create value of Sec-WebSocket-Accept header from inputted nonce.

acceptWebSocket

Upgrade inputted TCP connection into WebSocket connection.

createSecKey

Returns base64 encoded 16 bytes string for Sec-WebSocket-Key header.