Files
linker/linker.doc.web/docs/8、集成打洞到你的项目.md
2024-09-22 02:21:43 +08:00

2.1 KiB

sidebar_position
sidebar_position
8

8、集成打洞到你的项目

:::tip[说明]

  1. 你需要自己实现信标服务器,用于交换打洞信息
  2. linker.tunnel源码在https://github.com/snltty/linker/tree/master/linker.tunnel
  3. 使用nuget安装linker.tunnel

1、初始化

 //实现你的适配器
 ITunnelAdapter tunnelAdapter = new MyTunnelAdapter();

 //获取外网端口类列表
 List<ITunnelWanPortProtocol> tunnelWanPorts = new List<ITunnelWanPortProtocol>{
     new MyWanPort(),//你自己的获取外网端口的方法
 };
 //创建一个获取外网端口处理器
 TunnelWanPortTransfer tunnelWanPortTransfer = new TunnelWanPortTransfer();
 tunnelWanPortTransfer.Init(tunnelWanPorts);

 //打洞协议列表
 List<ITunnelTransport> transports = new List<ITunnelTransport>{
     new TransportUdp(),//udp打洞
     new TransportTcpP2PNAT()//tcp打洞
 };
 //创建一个打洞处理器
 TunnelTransfer tunnelTransfer = new TunnelTransfer();
 tunnelTransfer.Init(tunnelWanPortTransfer, tunnelAdapter, transports);

2、监听打洞成功事件

//监听打洞成功事件
tunnelTransfer.SetConnectedCallback("你的事务名",Action<ITunnelConnection> callback);
//移除打洞成功事件
tunnelTransfer.RemoveConnectedCallback("你的事务名",Action<ITunnelConnection> callback)

3、处理打洞消息


//开始打洞会调用ITunnelAdapter.SendConnectBegin 发送给对方,你需要实现这个方法
//对方收到消息,你应该调用
tunnelTransfer.OnBegin();

//打洞失败则会调用 ITunnelAdapter.SendConnectFail 发送给对方,你需要实现这个方法
//对方收到消息,你应该调用
tunnelTransfer.OnFail();

//打洞成功则会调用 ITunnelAdapter.SendConnectSuccess 发送给对方,你需要实现这个方法
//对方收到消息,你应该调用
tunnelTransfer.OnSuccess();

4、开始打洞


//会通过  ITunnelAdapter.SendConnectBegin 发送给对方,你需要实现这个方法
tunnelTransfer.ConnectAsync("对方的名字或编号,取决于的你信标服务器实现","事务名",TunnelProtocolType.None);

:::