gpt4 book ai didi

websocket - Deno:如何将 WebSocket 与 Oak 结合使用?

转载 作者:行者123 更新时间:2023-12-04 01:26:31 27 4
gpt4 key购买 nike

由于 Deno 于上周三发布,我尝试使用它并重做聊天应用程序的小示例,我尝试了以下操作:

import { Application, Router, send } from 'https://deno.land/x/oak/mod.ts';
import { listenAndServe } from 'https://deno.land/std/http/server.ts'

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

router
.get('/ws', handleSocket);


app.use(router.routes());
app.use(router.allowedMethods());

await app.listen({ port: HTTP_PORT });

应用程序
import { WebSocket, acceptWebSocket, isWebSocketCloseEvent, acceptable } from 'https://deno.land/std/ws/mod.ts'
import { v4 } from 'https://deno.land/std/uuid/mod.ts'

const users = new Map<string, WebSocket>()

export const handleSocket = async (ctx: any) => {
if (acceptable(ctx.request.serverRequest)) {
const { conn, r: bufReader, w: bufWriter, headers } = ctx.request.serverRequest;
const socket = await acceptWebSocket({
conn,
bufReader,
bufWriter,
headers,
});

await socketEventHandlers(socket);
} else {
throw new Error('Error when connecting websocket');
}
}
...

export const socketEventHandlers = async (ws: WebSocket): Promise<void> => {
// Register user connection
const userId = v4.generate()

users.set(userId, ws)
await broadcast(`> User with the id ${userId} is connected`)

// Wait for new messages
for await (const event of ws) {
const message = typeof event === 'string' ? event : ''

await broadcast(message, userId)

// Unregister user conection
if (!message && isWebSocketCloseEvent(event)) {
users.delete(userId)
await broadcast(`> User with the id ${userId} is disconnected`)
}
}
}


socket.ts

websocket 连接与 import { listenAndServe } from 'https://deno.land/std/http/server.ts'
完美配合,但使用上面的代码,我得到了类似 WebSocket connection to 'ws://localhost:3000/ws' failed: Invalid frame header 的错误.

有没有人有任何提示来解决它?谢谢 ;)

最佳答案

TL;DR - 自从回答被接受以来,这已经更新,现在更简单了。

router.get('/ws', async ctx => {
const sock = await ctx.upgrade();
handleSocket(sock);
});
信用 https://github.com/oakserver/oak/pull/137

关于websocket - Deno:如何将 WebSocket 与 Oak 结合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61835841/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com