【发布时间】:2020-07-30 16:02:05
【问题描述】:
大家早上好,
我正在试验 Deno 和 Oak 框架。我想在前端和后端之间建立一个 WebSocket 连接。我知道如何使用 Deno 标准库 ('HTTP') 来做到这一点,但是在尝试使用 Oak 时,我总是遇到错误。
我当前的代码是:
import { Application, Router } from "https://deno.land/x/oak@v6.0.1/mod.ts";
import { WebSocket, acceptWebSocket, isWebSocketCloseEvent, acceptable } from 'https://deno.land/std@0.61.0/ws/mod.ts';
import { staticFileMiddleware } from './staticFileMiddleware.ts';
const app = new Application();
const router = new Router();
router
.get('/', (ctx) => {
ctx.response.redirect('/index.html');
})
.get('/ws', async (ctx: any) => {
// console.log(ctx.request.serverRequest);
const sock = await ctx.upgrade();
let id = socks.push(sock) - 1;
for await (const ev of sock);
socks.splice(id, 1);
if (acceptable(ctx.request.serverRequest)) {
const { conn, r: bufReader, h: bufWriter, headers } = ctx.request.serverRequest;
const socket = await acceptWebSocket({
conn,
bufReader,
bufWriter,
headers
});
await chat(socket);
} else {
throw new Error('Error when connecting websocket');
}
});
app.use(router.routes());
app.use(router.allowedMethods());
app.use(staticFileMiddleware);
app.addEventListener('listen', ({hostname, port, secure}) => {
console.log(`Listening on ${secure ? 'https://' : 'http://'}${hostname || 'localhost'}:${port}`)
});
app.addEventListener('error', e => {
console.log(e.error);
});
await app.listen({ port: 3000 });
async function chat(ws: WebSocket) {
console.log(`Connected`);
for await (let data of ws) {
console.log(data, typeof data);
ws.send('Your message was successfully received');
if (isWebSocketCloseEvent(data)) {
console.log('Goodbye');
break;
}
}
}
我的静态文件中间件是:
import { Context, send } from "https://deno.land/x/oak@v6.0.1/mod.ts";
export const staticFileMiddleware = async (ctx: Context, next: Function) => {
const path = `${Deno.cwd()}/public${ctx.request.url.pathname}`;
if (await fileExists(path)) {
await send(ctx, ctx.request.url.pathname, {
root: `${Deno.cwd()}/public`
})
} else {
await next();
}
}
async function fileExists(path: string) {
try {
const stats = await Deno.lstat(path);
return stats && stats.isFile;
} catch (e) {
if (e && e instanceof Deno.errors.NotFound) {
return false;
} else {
throw e;
}
}
}
客户端代码包括:
let ws;
window.addEventListener('DOMContentLoaded', () => {
ws = new WebSocket(`ws://localhost:3000/ws`);
ws.addEventListener('open', onConnectionOpen);
ws.addEventListener('message', onMessageReceived);
});
function onConnectionOpen() {
console.log('Connection Opened');
ws.send('I am sending a message from the client side');
}
function onMessageReceived(event) {
console.log('Message Received', event);
}
我的文件结构如下:
server.ts
staticFileMiddleware.ts
/public
-client.js
-index.html
如果您能帮助我并为我指明正确的方向,我将不胜感激。 提前感谢您的帮助!!!
【问题讨论】:
-
你能分享你的错误信息吗
-
but when trying to use Oak, I keep running into errors。请分享错误。
标签: javascript http deno oak