如果是之前博客的老读者,那么相信对Deno Deploy不太陌生。之前的教程我利用Deno Deploy,给大家做了反代网站的教程。但是有些小伙伴是想使用反代来代理WebSocket节点的。不过,我们得感谢zizifn这位作者,让我们在Deno Deploy反代WebSocket节点变成了可能。在这篇教程中,我来和大家讲解一下如何使用Deno Deploy反代Websocket节点
准备材料
部署步骤
- 打开Deno Deploy的官网:https://deno.com/deploy ,点击“Sign up”进行注册。如有账号点击“Sign in”登录
- 点击“New Project”按钮,创建一个项目
- 点击“Play”按钮,创建一个新的项目
- 将代码修改为下面的内容,然后点击“Save and deploy”按钮(将
xx.xxx.xxxx
替换成实际的节点地址)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| import { serve } from "https://deno.land/[email protected]/http/server.ts";
const targetWSHost = "xx.xxx.xxxx"; async function handler(req: Request): Promise<Response> { const url = new URL(req.url); const upgrade = req.headers.get("upgrade") || ""; if (upgrade.toLowerCase() != "websocket") { url.host = targetWSHost; return await fetch(url, req); }
const socketPromse = []; const { socket: downstream, response } = Deno.upgradeWebSocket(req); downstream.addEventListener("open", ()=>{ console.log('open----downstream-------'); }) url.host = targetWSHost url.protocol = 'wss'; url.port = '443' const upstream = new WebSocket(url); socketPromse.push(new Promise((resolve) => upstream.addEventListener("open", resolve))); await Promise.all(socketPromse); console.log("Both WebSocket connections are open"); downstream.addEventListener("message", (message: any) => { upstream.send(message.data); }); downstream.addEventListener("error", (error: any) => { console.log("error", error); }); upstream.addEventListener("message", (message: any) => { downstream.send(message.data); }); upstream.addEventListener('error', (e: any) => { console.log("error", e); }); return response; }
serve(handler);
|
套餐价格