由于上周三发布了 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 });
应用程序.ts
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`)
}
}
}
套接字.ts
websocket 连接完美地import { listenAndServe } from 'https://deno.land/std/http/server.ts'
与WebSocket connection to 'ws://localhost:3000/ws' failed: Invalid frame header
.
有没有人有任何提示来解决它?谢谢 ;)