爱学习的好孩子

WebSocket server with Oak

时间: 2024-06-15

A WebSocket server written in Oak is different from the native WebSocket server only for the setup phase. This is because Oak uses similar looking, but different APIs for the WebSocket setup. Once the WebSocket connection is established, the other APIs like onopen, onmessage, onclose, onerror etc. are the same whether it’s Oak or native.

Setup phase

The setup phase consists of two simple steps:

  • Check if connection can be upgraded (isUpgradable)
  • If upgradable, upgrade it (upgrade)

These two simple APIs are part of the Oak’s Context object. These APIs take care of upgrading the underlying HTTP connection to a two-way WebSocket connection.

Example

import { Application } from "jsr:@oak/oak@16.1.0/application";
import { Router } from "jsr:@oak/oak@16.1.0/router";

const app = new Application({ logErrors: false });
const router = new Router();
router.get("/wss", (ctx) => {
  if (!ctx.isUpgradable) {
    ctx.throw(501);
  }
  const ws = ctx.upgrade();
  ws.onopen = () => {
    console.log("Connected to client");
    ws.send("Hello from server!");
  };
  ws.onmessage = (m) => {
    console.log("Got message from client: ", m.data);
    ws.close();
  };
  ws.onclose = () => console.log("Disconncted from client");
});
app.use(router.routes());
app.use(router.allowedMethods());
app.listen({ port: 8000 });

评论