无法使用Deno中的Oak WebSocket中间件从服务器发送消息回客户端。

huangapple go评论62阅读模式
英文:

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

问题

当使用下面的代码时,客户端永远不会收到echo2消息。第一条消息echo1,在等待之前被客户端接收到。如果我移除await,客户端会接收到两条消息。

我知道await在某种程度上中断了WebSocket。我漏掉了什么?

服务器端代码:

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;
      }
    }
  });
});

编辑:我使用了一个简单的WS客户端Chrome扩展来测试WebSocket,而不是编写显式代码。

英文:

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.

答案1

得分: 0

这个问题在我从 deno 版本 1.32.x 升级到 1.34.3 后自行解决了。

英文:

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

huangapple
  • 本文由 发表于 2023年7月3日 08:17:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76601237.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定