Menu Close

使用Deno Deploy反代Websocket节点

如果是之前博客的老读者,那么相信对Deno Deploy不太陌生。之前的教程我利用Deno Deploy,给大家做了反代网站的教程。但是有些小伙伴是想使用反代来代理WebSocket节点的。不过,我们得感谢zizifn这位作者,让我们在Deno Deploy反代WebSocket节点变成了可能。在这篇教程中,我来和大家讲解一下如何使用Deno Deploy反代Websocket节点

准备材料

  • GitHub 账号

部署步骤

  1. 打开Deno Deploy的官网:https://deno.com/deploy ,点击“Sign up”进行注册。如有账号点击“Sign in”登录

  1. 点击“New Project”按钮,创建一个项目

  1. 点击“Play”按钮,创建一个新的项目

  1. 将代码修改为下面的内容,然后点击“Save and deploy”按钮(将 xx.xxx.xxxx 替换成实际的节点地址)
import { serve } from "https://deno.land/std@0.177.0/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);
  });
  
  // Proxy messages from the upstream WebSocket connection to the downstream connection
  upstream.addEventListener("message", (message: any) => {
    downstream.send(message.data);
  });
  upstream.addEventListener('error', (e: any) => {
    console.log("error", e);
  });
  return response;
}

serve(handler);

套餐价格

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注