英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论