websocketdenooak

Unable to send messages back to the client from the server using Oak websocket middleware in Deno


When using the below code, the echo2 message is never received by the client. The first message, echo1 -- which is prior to the await, is received by the client. If I remove the await, both messages are received by the client.

I know the await is somehow interrupting the websocket. What am I missing?

Server Code:

import {
  Application,
  Router
} from "https://deno.land/x/oak@v12.1.0/mod.ts";

const app = new Application();
const router = new Router();

async function pause(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

router.get("/ws", (ctx) => {
  console.log("ws connected");
  if (!ctx.isUpgradable) {
    ctx.throw(501);
  }
  const ws = ctx.upgrade();

  ws.onopen = () => {
    ws.send(JSON.stringify({ intent: "init", id: "test" }));
  };

  ws.addEventListener("message", async (ev) => {
    const d = JSON.parse(ev.data);
    console.log("got message", d);
    switch (d.intent) {
      case "echo": {
        ws.send(JSON.stringify({ intent: "echo1", data: { empty: true } }));
        await pause(1000);
        ws.send(JSON.stringify({ intent: "echo2", data: { empty: true } }));
        break;
      }
    }
  });
});

EDIT: I was using a simple WS client chrome extension to test the websocket, not writing explicit code.


Solution

  • This issue resolved itself when I upgraded from deno 1.32.x to 1.34.3.