/// <summary> /// 保存端口映射配置到配置文件 /// </summary> /// <param name="item">要保存的配置项</param> /// <param name="configTemp">配置文件内容缓存</param> /// <param name="handleDictionary">配置内容解析处理器实例</param> private void SavePortMapItem(PortMapItem item, List <string> configTemp, Dictionary <string, IConfigIO> handleDictionary) { //端口映射 解析处理器名称 string handlerName = "[PortMapItem]"; //解析处理器实例 IConfigIO handler; if (handleDictionary.ContainsKey(handlerName)) { handler = handleDictionary[handlerName]; } else { throw new NotSupportedException($"未找到对应的处理器 {handlerName}"); } int rIndex = configTemp.IndexOf(handlerName); if (rIndex >= 0) { //找到相应位置,并插值 configTemp.Insert(rIndex + 1, handler.GetItemString(item)); } else { //没有找到相应节点,添加区块到末尾 configTemp.Add(handlerName); configTemp.Add(handler.GetItemString(item)); } //覆盖配置文件 ForeachWrite(configTemp); }
public void Start(string pipeName = "") { pipeServer = new w_pipe.PipeServer(); pipeServer.StartListen(pipeName); EasyInject.Get <ILogger>().OnWriteLog += PipeServer_OnWriteLog; //订阅“命令”消息 pipeServer.RegisterHandler <string>("ExcuteCmd", ReadCallBack); //订阅“获取监听端口”消息 pipeServer.RegisterHandler <string>("GetListenPorts", (_, pipe) => { string ret = ""; for (int i = 0; i < appCenter.Config.PortMapList.Count; i++) { PortMapItem item = appCenter.Config.PortMapList[i]; if (i != appCenter.Config.PortMapList.Count - 1) { ret += item.LocalPort + ","; } else { ret += item.LocalPort; } } //发送“监听端口”信息 w_pipe.PipeServer.SendMsg(pipe, "GetListenPorts_R", ret); }); //订阅“获取版本”消息 pipeServer.RegisterHandler <string>("GetVersionInfo", (_, pipe) => { //发送“版本信息” w_pipe.PipeServer.SendMsg(pipe, "GetVersionInfo_R", EasyInject.Get <AppCenter>().SoftVerSion); }); }
private void ListenPortMapPortWithServerName(PortMapItem item) { //服务端口限制在1000以上 if (item.LocalPort > 1000) { try { TcpListener listener = new TcpListener(IPAddress.Any, item.LocalPort); listener.Start(); ConsoleUtils.WriteLine($"Server:端口映射:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}"); Global.TaskFactory.StartNew(() => { while (true) { Socket socket = listener.AcceptSocket(); P2PTcpClient tcpClient = new P2PTcpClient(socket); Global.TaskFactory.StartNew(() => { string token = tcpClient.Token; //获取目标tcp if (Global.TcpMap.ContainsKey(item.RemoteAddress) && Global.TcpMap[item.RemoteAddress].Connected) { //加入待连接集合 Global.WaiteConnetctTcp.Add(token, tcpClient); //发送p2p申请 Models.Send.Port2PApplyRequest packet = new Models.Send.Port2PApplyRequest(token, item.RemotePort); Debug.WriteLine("[服务器]发送Port2P连接申请"); Global.TcpMap[item.RemoteAddress].Client.Send(packet.PackData()); Global.TaskFactory.StartNew(() => { Thread.Sleep(Global.P2PTimeout); //如果5秒后没有匹配成功,则关闭连接 if (Global.WaiteConnetctTcp.ContainsKey(token)) { Debug.WriteLine("[服务器]5秒无响应,关闭连接"); Global.WaiteConnetctTcp[token].Close(); Global.WaiteConnetctTcp.Remove(token); } }); } else { Debug.WriteLine($"[服务器][错误]端口映射:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}服务不在线."); tcpClient.Close(); } }); } }); } catch { ConsoleUtils.WriteLine($"Server:端口映射{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}创建失败."); throw new Exception($"端口映射{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}创建失败."); } } else { ConsoleUtils.WriteLine($"Server:端口必须大于1000,当前端口:{item.LocalPort}"); } }
/// <summary> /// 直接转发类型的端口监听 /// </summary> /// <param name="item"></param> private void ListenPortMapPortWithIp(PortMapItem item) { TcpListener listener = null; EasyOp.Do(() => { listener = new TcpListener(IPAddress.Any, item.LocalPort); listener.Start(); }, () => { ListenerList.Add(listener); ListenSt listenSt = new ListenSt(); listenSt.listener = listener; listenSt.item = item; EasyOp.Do(() => { listener.BeginAcceptSocket(AcceptSocket_Ip, listenSt); LogUtils.Info($"端口映射:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}", false); }, ex => { LogUtils.Error($"建立端口映射失败 {item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}{Environment.NewLine}{ex}"); EasyOp.Do(() => listener.Stop()); ListenerList.Remove(listener); }); }, ex => { LogUtils.Error($"建立端口映射失败 {item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}{Environment.NewLine}{ex}"); }); }
public void P2PBind_DirectConnect(P2PTcpClient p2pClient, string token) { try { if (m_tcpClient.P2PLocalPort > 0) { int port = m_tcpClient.P2PLocalPort; PortMapItem destMap = ConfigCenter.Instance.PortMapList.FirstOrDefault(t => t.LocalPort == port && string.IsNullOrEmpty(t.LocalAddress)); P2PTcpClient portClient = null; if (destMap != null) { if (destMap.MapType == PortMapType.ip) { portClient = new P2PTcpClient(destMap.RemoteAddress, destMap.RemotePort); } else { portClient = new P2PTcpClient("127.0.0.1", port); } } else { portClient = new P2PTcpClient("127.0.0.1", port); } portClient.IsAuth = p2pClient.IsAuth = true; portClient.ToClient = p2pClient; p2pClient.ToClient = portClient; AppCenter.Instance.StartNewTask(() => { Global_Func.BindTcp(p2pClient, portClient); }); AppCenter.Instance.StartNewTask(() => { Global_Func.BindTcp(portClient, p2pClient); }); } else { if (TcpCenter.Instance.WaiteConnetctTcp.ContainsKey(token)) { P2PTcpClient portClient = TcpCenter.Instance.WaiteConnetctTcp[token]; TcpCenter.Instance.WaiteConnetctTcp.Remove(token); portClient.IsAuth = p2pClient.IsAuth = true; portClient.ToClient = p2pClient; p2pClient.ToClient = portClient; AppCenter.Instance.StartNewTask(() => { Global_Func.BindTcp(p2pClient, portClient); }); AppCenter.Instance.StartNewTask(() => { Global_Func.BindTcp(portClient, p2pClient); }); } else { LogUtils.Warning($"命令:0x0201 接收到内网穿透命令,但已超时. token:{token}"); } } } catch (Exception ex) { LogUtils.Error(ex.Message); } }
/// <summary> /// 匹配端口映射配置(端口相同即匹配成功) /// </summary> /// <param name="tItem">配置文件项</param> /// <param name="item">用户提供的项</param> /// <param name="matchedFunc">匹配成功时执行的方法</param> /// <returns></returns> private bool MatchPortMapItem(PortMapItem tItem, PortMapItem item, Action matchedFunc = null) { if (tItem != null && tItem.LocalPort == item.LocalPort) { matchedFunc?.Invoke(); return(true); } return(false); }
private void ListenPortMapPortWithServerName(PortMapItem item) { TcpListener listener = new TcpListener(string.IsNullOrEmpty(item.LocalAddress) ? IPAddress.Any : IPAddress.Parse(item.LocalAddress), item.LocalPort); try { listener.Start(); } catch (SocketException ex) { LogUtils.Error($"端口映射失败:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}{Environment.NewLine}{ex.Message}"); } ListenerList.Add(listener); LogUtils.Show($"端口映射成功:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}"); Global.TaskFactory.StartNew(() => { while (true) { Socket socket = listener.AcceptSocket(); //获取目标tcp if (Global.P2PServerTcp != null && Global.P2PServerTcp.Connected) { Global.TaskFactory.StartNew(() => { P2PTcpClient tcpClient = new P2PTcpClient(socket); //加入待连接集合 Global.WaiteConnetctTcp.Add(tcpClient.Token, tcpClient); //发送p2p申请 Send_0x0201_Apply packet = new Send_0x0201_Apply(tcpClient.Token, item.RemoteAddress, item.RemotePort); LogUtils.Info($"正在建立内网穿透(3端)通道 token:{tcpClient.Token} client:{item.RemoteAddress} port:{item.RemotePort}"); try { Global.P2PServerTcp.Client.Send(packet.PackData()); } finally { //如果5秒后没有匹配成功,则关闭连接 Thread.Sleep(Global.P2PTimeout); if (Global.WaiteConnetctTcp.ContainsKey(tcpClient.Token)) { LogUtils.Warning($"内网穿透失败:token:{tcpClient.Token} {item.LocalPort}->{item.RemoteAddress}:{item.RemotePort} {Global.P2PTimeout}秒无响应,已超时."); Global.WaiteConnetctTcp[tcpClient.Token].Close(); Global.WaiteConnetctTcp.Remove(tcpClient.Token); } } }); } else { LogUtils.Warning($"内网穿透失败:未连接到服务器!"); socket.Close(); } } }); }
/// <summary> /// 添加/修改指定端口映射 /// </summary> /// <param name="item"></param> /// <returns></returns> public bool UsePortMapItem(PortMapItem item) { if (tcpCenter.ListenerList.Any(t => t.Key.Item2 == item.LocalPort)) { List <(string, int)> keys = new List <(string, int)>(); tcpCenter.ListenerList.Where(t => t.Key.Item2 == item.LocalPort).ToList().ForEach(t => { t.Value.Stop(); keys.Add(t.Key); }); keys.ForEach(key => tcpCenter.ListenerList.Remove(key)); appCenter.Config.PortMapList = appCenter.Config.PortMapList.Where(t => t.LocalPort != item.LocalPort).ToList(); } return(ListenPortMap(item)); }
/// <summary> /// 监听指定类型端口映射 /// </summary> /// <param name="item"></param> /// <returns></returns> internal bool ListenPortMap(PortMapItem item) { if (item.MapType == PortMapType.ip) { return(ListenPortMapPort_Ip(item)); } else { return(ListenPortMapPort_Server(item)); } }
private void ListenPortMapPortWithServerName(PortMapItem item) { TcpListener listener = new TcpListener(IPAddress.Any, item.LocalPort); try { listener.Start(); } catch (Exception ex) { LogUtils.Error($"【失败】端口映射:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}{Environment.NewLine}{ex.ToString()}"); return; } ListenerList.Add(listener); LogUtils.Show($"【成功】端口映射:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}"); Global.TaskFactory.StartNew(() => { while (true) { Socket socket = listener.AcceptSocket(); P2PTcpClient tcpClient = new P2PTcpClient(socket); Global.TaskFactory.StartNew(() => { string token = tcpClient.Token; //获取目标tcp if (Global.TcpMap.ContainsKey(item.RemoteAddress) && Global.TcpMap[item.RemoteAddress].TcpClient.Connected) { //加入待连接集合 Global.WaiteConnetctTcp.Add(token, tcpClient); //发送p2p申请 Models.Send.Send_0x0211 packet = new Models.Send.Send_0x0211(token, item.RemotePort); Global.TcpMap[item.RemoteAddress].TcpClient.Client.Send(packet.PackData()); Global.TaskFactory.StartNew(() => { Thread.Sleep(Global.P2PTimeout); //如果5秒后没有匹配成功,则关闭连接 if (Global.WaiteConnetctTcp.ContainsKey(token)) { LogUtils.Warning($"【失败】内网穿透:{Global.P2PTimeout}秒无响应,已超时."); Global.WaiteConnetctTcp[token].Close(); Global.WaiteConnetctTcp.Remove(token); } }); } else { LogUtils.Warning($"【失败】内网穿透:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort} 客户端不在线!"); tcpClient.Close(); } }); } }); }
private void ListenPortMapPortWithServerName(PortMapItem item) { try { TcpListener listener = new TcpListener(string.IsNullOrEmpty(item.LocalAddress) ? IPAddress.Any : IPAddress.Parse(item.LocalAddress), item.LocalPort); listener.Start(); ListenerList.Add(listener); LogUtils.Show($"【成功】端口映射:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}"); Global.TaskFactory.StartNew(() => { while (true) { Socket socket = listener.AcceptSocket(); P2PTcpClient tcpClient = new P2PTcpClient(socket); Global.TaskFactory.StartNew(() => { string token = tcpClient.Token; //获取目标tcp if (Global.P2PServerTcp != null && Global.P2PServerTcp.Connected) { //加入待连接集合 Global.WaiteConnetctTcp.Add(token, tcpClient); //发送p2p申请 Send_0x0201_Apply packet = new Send_0x0201_Apply(token, item.RemoteAddress, item.RemotePort); Global.P2PServerTcp.Client.Send(packet.PackData()); //LogUtils.Debug("P2P第一步:向服务器发送申请."); Global.TaskFactory.StartNew(() => { Thread.Sleep(Global.P2PTimeout); //如果5秒后没有匹配成功,则关闭连接 if (Global.WaiteConnetctTcp.ContainsKey(token)) { LogUtils.Warning($"【失败】内网穿透:{Global.P2PTimeout}秒无响应,已超时."); Global.WaiteConnetctTcp[token].Close(); Global.WaiteConnetctTcp.Remove(token); } }); } else { LogUtils.Warning($"【失败】内网穿透:未连接服务器!"); tcpClient.Close(); } }); } }); } catch (Exception ex) { LogUtils.Error($"【失败】端口映射:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}{Environment.NewLine}{ex.ToString()}"); } }
/// <summary> /// 直接转发类型的端口监听 /// </summary> /// <param name="item"></param> private void ListenPortMapPortWithIp(PortMapItem item) { //服务端口限制在1000以上 if (item.LocalPort > 1000) { try { TcpListener listener = new TcpListener(IPAddress.Any, item.LocalPort); listener.Start(); ConsoleUtils.WriteLine($"Server:端口映射:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}"); Global.TaskFactory.StartNew(() => { while (true) { Socket socket = listener.AcceptSocket(); P2PTcpClient tcpClient = new P2PTcpClient(socket); Global.TaskFactory.StartNew(() => { try { P2PTcpClient ipClient = new P2PTcpClient(item.RemoteAddress, item.RemotePort); tcpClient.ToClient = ipClient; ipClient.ToClient = tcpClient; } catch { tcpClient.Close(); Debug.WriteLine($"端口{item.LocalPort}映射关闭,无法建立{item.RemoteAddress}:{item.RemotePort}tcp连接."); } if (tcpClient.Connected) { Global.TaskFactory.StartNew(() => { ListenPortMapTcpWithIp(tcpClient); }); Global.TaskFactory.StartNew(() => { ListenPortMapTcpWithIp(tcpClient.ToClient); }); } }); } }); } catch { ConsoleUtils.WriteLine($"Server:端口映射{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}创建失败."); throw new Exception($"端口映射{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}创建失败."); } } else { ConsoleUtils.WriteLine($"Server:端口必须大于1000,当前端口:{item.LocalPort}"); } }
/// <summary> /// 直接转发类型的端口监听,接收新tcp回调方法 /// </summary> /// <param name="ar"></param> public void AcceptSocket_Ip(IAsyncResult ar) { ListenSt st = (ListenSt)ar.AsyncState; TcpListener listener = st.listener; PortMapItem item = st.item; Socket socket = null; try { socket = listener.EndAcceptSocket(ar); } catch (Exception ex) { LogUtils.Error(ex.ToString()); return; } listener.BeginAcceptSocket(AcceptSocket_Ip, st); P2PTcpClient tcpClient = new P2PTcpClient(socket); P2PTcpClient ipClient = null; try { ipClient = new P2PTcpClient(item.RemoteAddress, item.RemotePort); } catch (Exception ex) { tcpClient?.SafeClose(); LogUtils.Debug($"建立隧道失败:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}{Environment.NewLine}{ex}"); } if (ipClient.Connected) { tcpClient.ToClient = ipClient; ipClient.ToClient = tcpClient; RelationTcp toRelation = new RelationTcp(); toRelation.readTcp = tcpClient; toRelation.readSs = tcpClient.GetStream(); toRelation.writeTcp = tcpClient.ToClient; toRelation.writeSs = tcpClient.ToClient.GetStream(); toRelation.buffer = new byte[P2PGlobal.P2PSocketBufferSize]; RelationTcp fromRelation = new RelationTcp(); fromRelation.readTcp = toRelation.writeTcp; fromRelation.readSs = toRelation.writeSs; fromRelation.writeTcp = toRelation.readTcp; fromRelation.writeSs = toRelation.readSs; fromRelation.buffer = new byte[P2PGlobal.P2PSocketBufferSize]; StartTransferTcp_Ip(toRelation); StartTransferTcp_Ip(fromRelation); } }
/// <summary> /// 直接转发类型的端口监听 /// </summary> /// <param name="item"></param> private void ListenPortMapPortWithIp(PortMapItem item) { TcpListener listener = null; try { listener = new TcpListener(string.IsNullOrEmpty(item.LocalAddress) ? IPAddress.Any : IPAddress.Parse(item.LocalAddress), item.LocalPort); listener.Start(); } catch (Exception ex) { LogUtils.Error($"添加端口映射失败:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}{Environment.NewLine}{ex.ToString()}"); return; } TcpCenter.Instance.ListenerList.Add($"{item.LocalAddress}:{item.LocalPort}", listener); LogUtils.Info($"添加端口映射成功:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}", false); AppCenter.Instance.StartNewTask(() => { while (true) { Socket socket = listener.AcceptSocket(); P2PTcpClient tcpClient = new P2PTcpClient(socket); AppCenter.Instance.StartNewTask(() => { P2PTcpClient ipClient = null; try { ipClient = new P2PTcpClient(item.RemoteAddress, item.RemotePort); } catch (Exception ex) { tcpClient.SafeClose(); LogUtils.Error($"内网穿透失败:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}{Environment.NewLine}{ex}"); } if (ipClient.Connected) { tcpClient.ToClient = ipClient; ipClient.ToClient = tcpClient; AppCenter.Instance.StartNewTask(() => ListenPortMapTcpWithIp(tcpClient)); AppCenter.Instance.StartNewTask(() => ListenPortMapTcpWithIp(tcpClient.ToClient)); } }); } }); }
/// <summary> /// 直接转发类型的端口监听 /// </summary> /// <param name="item"></param> private void ListenPortMapPortWithIp(PortMapItem item) { TcpListener listener = new TcpListener(string.IsNullOrEmpty(item.LocalAddress) ? IPAddress.Any : IPAddress.Parse(item.LocalAddress), item.LocalPort); try { listener.Start(); } catch (Exception ex) { LogUtils.Error($"端口映射失败:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}{Environment.NewLine}{ex.ToString()}"); } ListenerList.Add(listener); LogUtils.Show($"端口映射成功:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}"); Global.TaskFactory.StartNew(() => { while (true) { Socket socket = listener.AcceptSocket(); P2PTcpClient tcpClient = new P2PTcpClient(socket); Global.TaskFactory.StartNew(() => { P2PTcpClient ipClient = null; try { ipClient = new P2PTcpClient(item.RemoteAddress, item.RemotePort); } catch (Exception ex) { tcpClient.Close(); LogUtils.Error($"内网穿透失败:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}{Environment.NewLine}{ex}"); } if (ipClient.Connected) { tcpClient.ToClient = ipClient; ipClient.ToClient = tcpClient; Global.TaskFactory.StartNew(() => ListenPortMapTcpWithIp(tcpClient)); Global.TaskFactory.StartNew(() => ListenPortMapTcpWithIp(tcpClient.ToClient)); } }); } }); }
/// <summary> /// 直接转发类型的端口监听 /// </summary> /// <param name="item"></param> private void ListenPortMapPortWithIp(PortMapItem item) { TcpListener listener = new TcpListener(IPAddress.Any, item.LocalPort); try { listener.Start(); } catch (Exception ex) { LogUtils.Error($"【失败】端口映射:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}{Environment.NewLine}{ex.ToString()}"); return; } ListenerList.Add(listener); LogUtils.Show($"【成功】端口映射:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}"); Global.TaskFactory.StartNew(() => { while (true) { Socket socket = listener.AcceptSocket(); P2PTcpClient tcpClient = new P2PTcpClient(socket); Global.TaskFactory.StartNew(() => { try { P2PTcpClient ipClient = new P2PTcpClient(item.RemoteAddress, item.RemotePort); tcpClient.ToClient = ipClient; ipClient.ToClient = tcpClient; } catch (Exception ex) { tcpClient.Close(); LogUtils.Error($"【失败】内网穿透:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}{Environment.NewLine}{ex.ToString()}"); } if (tcpClient.Connected) { Global.TaskFactory.StartNew(() => { ListenPortMapTcpWithIp(tcpClient); }); Global.TaskFactory.StartNew(() => { ListenPortMapTcpWithIp(tcpClient.ToClient); }); } }); } }); }
/// <summary> /// 直接转发类型的端口监听 /// </summary> /// <param name="item"></param> private bool ListenPortMapPort_Ip(PortMapItem item) { bool ret = true; TcpListener listener = null; EasyOp.Do(() => { listener = new TcpListener(string.IsNullOrEmpty(item.LocalAddress) ? IPAddress.Any : IPAddress.Parse(item.LocalAddress), item.LocalPort); listener.Start(); }, () => { tcpCenter.ListenerList.Add((item.LocalAddress, item.LocalPort), listener); LogUtils.Info($"添加端口映射成功:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}", false); ListenSt listenSt = new ListenSt(); listenSt.listener = listener; listenSt.item = item; listener.BeginAcceptSocket(AcceptSocket_Ip, listenSt); },
/// <summary> /// 从目标端创建与服务器的tcp连接 /// </summary> /// <param name="token"></param> public void CreateTcpFromDest(string token) { try { Models.Send.Send_0x0201_Bind sendPacket = new Models.Send.Send_0x0201_Bind(token); Utils.LogUtils.Info($"命令:0x0201 正在绑定内网穿透(3端)通道 token:{token}"); int port = BinaryUtils.ReadInt(data); PortMapItem destMap = ConfigCenter.Instance.PortMapList.FirstOrDefault(t => t.LocalPort == port && string.IsNullOrEmpty(t.LocalAddress)); P2PTcpClient portClient = null; if (destMap != null) { if (destMap.MapType == PortMapType.ip) { portClient = new P2PTcpClient(destMap.RemoteAddress, destMap.RemotePort); } else { portClient = new P2PTcpClient("127.0.0.1", port); } } else { portClient = new P2PTcpClient("127.0.0.1", port); } P2PTcpClient serverClient = new P2PTcpClient(ConfigCenter.Instance.ServerAddress, ConfigCenter.Instance.ServerPort); portClient.IsAuth = serverClient.IsAuth = true; portClient.ToClient = serverClient; serverClient.ToClient = portClient; serverClient.Client.Send(sendPacket.PackData()); AppCenter.Instance.StartNewTask(() => { Global_Func.ListenTcp <ReceivePacket>(serverClient); }); } catch (Exception ex) { LogUtils.Error($"命令:0x0201 绑定内网穿透(3端)通道错误:{Environment.NewLine}{ex.Message}"); } }
/// <summary> /// 从目标端创建与服务器的tcp连接 /// </summary> /// <param name="token"></param> public void CreateTcpFromDest(string token) { try { Models.Send.Send_0x0201_Bind sendPacket = new Models.Send.Send_0x0201_Bind(token); int port = BinaryUtils.ReadInt(m_data); PortMapItem destMap = Global.PortMapList.FirstOrDefault(t => t.LocalPort == port && string.IsNullOrEmpty(t.LocalAddress)); P2PTcpClient portClient = null; if (destMap != null) { if (destMap.MapType == PortMapType.ip) { portClient = new P2PTcpClient(destMap.RemoteAddress, destMap.RemotePort); } else { portClient = new P2PTcpClient("127.0.0.1", port); } } else { portClient = new P2PTcpClient("127.0.0.1", port); } P2PTcpClient serverClient = new P2PTcpClient(Global.ServerAddress, Global.ServerPort); portClient.IsAuth = serverClient.IsAuth = true; portClient.ToClient = serverClient; serverClient.ToClient = portClient; serverClient.Client.Send(sendPacket.PackData()); Global.TaskFactory.StartNew(() => { Global_Func.ListenTcp <ReceivePacket>(serverClient); }); } catch (Exception ex) { LogUtils.Error($"【P2P】命令:0x0201 错误:{Environment.NewLine}{ex.ToString()}"); } }
/// <summary> /// 端口映射监听端口的新tcp回调方法 /// </summary> /// <param name="ar"></param> public void AcceptSocket_Server(IAsyncResult ar) { ListenSt st = (ListenSt)ar.AsyncState; TcpListener listener = st.listener; PortMapItem item = st.item; Socket socket = null; try { //获取当前接入的tcp socket = listener.EndAcceptSocket(ar); } catch (Exception ex) { LogUtils.Error(ex.ToString()); return; } EasyOp.Do(() => { listener.BeginAcceptSocket(AcceptSocket_Server, st); }, () => { EasyOp.Do(() => { if (!CreateP2PConnect(item, socket)) { EasyOp.Do(socket.SafeClose); } }, ex => { LogUtils.Debug("处理新tcp连接时发生错误:" + Environment.NewLine + ex.ToString()); }); }, ex => { LogUtils.Error("监听端口发生错误:" + listener.LocalEndpoint.ToString() + Environment.NewLine + ex.ToString()); }); }
/// <summary> /// 监听需要服务端的端口映射 /// </summary> /// <param name="item"></param> /// <returns></returns> private bool ListenPortMapPort_Server(PortMapItem item) { TcpListener listener = null; try { listener = new TcpListener(string.IsNullOrEmpty(item.LocalAddress) ? IPAddress.Any : IPAddress.Parse(item.LocalAddress), item.LocalPort); listener.Start(); } catch (SocketException ex) { LogUtils.Error($"端口映射失败:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}{Environment.NewLine}{ex.Message}"); return(false); } tcpCenter.ListenerList.Add((item.LocalAddress, item.LocalPort), listener); LogUtils.Info($"端口映射:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}", false); ListenSt listenSt = new ListenSt(); listenSt.listener = listener; listenSt.item = item; listener.BeginAcceptSocket(AcceptSocket_Server, listenSt); return(true); }
public static void LoadFromFile() { int mode = 0; using (StreamReader fs = new StreamReader(Global.ConfigFile)) { while (!fs.EndOfStream) { string lineStr = fs.ReadLine().Trim(); if (lineStr.Length > 0 && !lineStr.StartsWith("#")) { if (lineStr == "[Common]") { mode = 1; } else if (lineStr == "[PortMapItem]") { mode = 2; } else if (mode == 1) { string[] splitStr = lineStr.Split('='); switch (splitStr[0].ToLower()) { case "port": { Global.LocalPort = Convert.ToInt32(splitStr[1]); } break; case "loglevel": { string levelName = splitStr[1].ToLower(); switch (levelName) { case "debug": LogUtils.Instance.LogLevel = Core.Utils.LogLevel.Debug; break; case "error": LogUtils.Instance.LogLevel = Core.Utils.LogLevel.Error; break; case "info": LogUtils.Instance.LogLevel = Core.Utils.LogLevel.Info; break; case "none": LogUtils.Instance.LogLevel = Core.Utils.LogLevel.None; break; case "warning": LogUtils.Instance.LogLevel = Core.Utils.LogLevel.Warning; break; default: LogUtils.Instance.LogLevel = Core.Utils.LogLevel.None; break; } } break; case "allowclient": { string[] clientItems = splitStr[1].Split(','); foreach (string clientItem in clientItems) { ClientItem item = new ClientItem(); string[] authItem = clientItem.Split(':'); if (authItem.Length == 1) { item.ClientName = authItem[0]; } else if (authItem.Length == 2) { item.ClientName = authItem[0]; item.AuthCode = authItem[1]; } else { continue; } Global.ClientAuthList.Add(item); } } break; } } else if (mode == 2) { int centerSplitIndexOf = lineStr.IndexOf("->"); string localStr = lineStr.Substring(0, centerSplitIndexOf); string remoteStr = lineStr.Substring(centerSplitIndexOf + 2); string[] localStrList = localStr.Split(':'); string localIp = localStrList.Length >= 2 ? localStrList[0] : ""; string portStr = localStrList.Length >= 2 ? localStrList[1] : localStr; int port = 0; if (int.TryParse(portStr, out port) && port > 0) { if (!Global.PortMapList.Any(t => t.LocalPort == port)) { PortMapItem item = new PortMapItem(); string[] remoteStrList = remoteStr.Split(':'); item.LocalPort = port; item.LocalAddress = localIp; if (remoteStrList[0].StartsWith("[") && remoteStrList[0].EndsWith("]")) { item.MapType = PortMapType.servername; item.RemoteAddress = remoteStrList[0].Substring(1, remoteStrList[0].Length - 2); } else { item.MapType = PortMapType.ip; item.RemoteAddress = remoteStrList[0]; } item.RemotePort = Convert.ToInt32(remoteStrList[1]); Global.PortMapList.Add(item); } } } } } } }
public void AcceptSocket_Ip(IAsyncResult ar) { ListenSt st = (ListenSt)ar.AsyncState; TcpListener listener = st.listener; PortMapItem item = st.item; Socket socket = null; EasyOp.Do(() => { socket = listener.EndAcceptSocket(ar); }, () => { EasyOp.Do(() => { listener.BeginAcceptSocket(AcceptSocket_Ip, st); }, ex => { LogUtils.Error($"端口监听失败:{Environment.NewLine}{ex}"); }); P2PTcpClient tcpClient = null; EasyOp.Do(() => { tcpClient = new P2PTcpClient(socket); }, () => { P2PTcpClient ipClient = null; EasyOp.Do(() => { ipClient = new P2PTcpClient(item.RemoteAddress, item.RemotePort); }, () => { tcpClient.ToClient = ipClient; ipClient.ToClient = tcpClient; RelationTcp toRelation = new RelationTcp(); toRelation.readTcp = tcpClient; toRelation.writeTcp = tcpClient.ToClient; toRelation.buffer = new byte[P2PGlobal.P2PSocketBufferSize]; RelationTcp fromRelation = new RelationTcp(); fromRelation.readTcp = toRelation.writeTcp; fromRelation.writeTcp = toRelation.readTcp; fromRelation.buffer = new byte[P2PGlobal.P2PSocketBufferSize]; EasyOp.Do(() => { StartTransferTcp_Ip(toRelation); StartTransferTcp_Ip(fromRelation); }, ex => { LogUtils.Debug($"建立隧道失败:{Environment.NewLine}{ex}"); EasyOp.Do(() => ipClient.SafeClose()); EasyOp.Do(() => tcpClient.SafeClose()); }); }, ex => { LogUtils.Debug($"建立隧道失败:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}{Environment.NewLine}{ex}"); EasyOp.Do(() => tcpClient.SafeClose()); }); }, ex => { LogUtils.Debug($"处理新接入Tcp时发生错误:{Environment.NewLine}{ex}"); EasyOp.Do(() => socket?.SafeClose()); }); }, ex => { LogUtils.Debug($"获取新接入的Tcp连接失败:{Environment.NewLine}{ex}"); EasyOp.Do(() => { listener.BeginAcceptSocket(AcceptSocket_Ip, st); }, exx => { LogUtils.Error($"端口监听失败:{Environment.NewLine}{exx}"); }); }); }
public static void LoadFromFile() { int mode = 0; using (StreamReader fs = new StreamReader(Global.ConfigFile)) { while (!fs.EndOfStream) { string lineStr = fs.ReadLine().Trim(); if (lineStr.Length > 0 && !lineStr.StartsWith("#")) { if (lineStr == "[Common]") { mode = 1; } else if (lineStr == "[PortMapItem]") { mode = 2; } else if (mode == 1) { string[] splitStr = lineStr.Split('='); switch (splitStr[0].ToLower()) { case "port": { Global.LocalPort = Convert.ToInt32(splitStr[1]); } break; } } else if (mode == 2) { string[] splitStr = lineStr.Split(new char[2] { '-', '>' }); int port = 0; if (int.TryParse(splitStr[0], out port) && port > 0) { if (!Global.PortMapList.Any(t => t.LocalPort == port)) { string[] remoteStr = splitStr[2].Split(':'); PortMapItem item = new PortMapItem(); item.LocalPort = port; if (remoteStr[0].StartsWith("[") && remoteStr[0].EndsWith("]")) { item.MapType = PortMapType.servername; item.RemoteAddress = remoteStr[0].Substring(1, remoteStr[0].Length - 2); } else { item.MapType = PortMapType.ip; item.RemoteAddress = remoteStr[0]; } item.RemotePort = Convert.ToInt32(remoteStr[1]); Global.PortMapList.Add(item); } } } } } } }
/// <summary> /// 端口映射监听端口的新tcp回调方法 /// </summary> /// <param name="ar"></param> public void AcceptSocket_Server(IAsyncResult ar) { ListenSt st = (ListenSt)ar.AsyncState; TcpListener listener = st.listener; PortMapItem item = st.item; Socket socket = null; try { //获取当前接入的tcp socket = listener.EndAcceptSocket(ar); } catch (Exception ex) { LogUtils.Error(ex.ToString()); return; } try { listener.BeginAcceptSocket(AcceptSocket_Server, st); } catch (Exception ex) { LogUtils.Error("监听端口发生错误:" + listener.LocalEndpoint.ToString() + Environment.NewLine + ex.ToString()); } try { if (tcpCenter.P2PServerTcp != null && tcpCenter.P2PServerTcp.Connected) { P2PTcpClient tcpClient = new P2PTcpClient(socket); //加入待连接集合 tcpCenter.WaiteConnetctTcp.Add(tcpClient.Token, tcpClient); //发送消息给服务端,开始内网穿透 Send_0x0201_Apply packet = new Send_0x0201_Apply(tcpClient.Token, item.RemoteAddress, item.RemotePort, item.P2PType); LogUtils.Debug(string.Format("正在建立{0}隧道 token:{1} client:{2} port:{3}", item.P2PType == 0 ? "中转模式" : "P2P模式", tcpClient.Token, item.RemoteAddress, item.RemotePort)); byte[] dataAr = packet.PackData(); EasyOp.Do(() => { tcpCenter.P2PServerTcp.BeginSend(dataAr); }, () => { //等待指定超时时间后,判断是否连接成功 Thread.Sleep(AppConfig.P2PTimeout); if (tcpCenter.WaiteConnetctTcp.ContainsKey(tcpClient.Token)) { LogUtils.Debug($"建立隧道失败:token:{tcpClient.Token} {item.LocalPort}->{item.RemoteAddress}:{item.RemotePort} {AppConfig.P2PTimeout / 1000}秒无响应,已超时."); tcpCenter.WaiteConnetctTcp[tcpClient.Token]?.SafeClose(); tcpCenter.WaiteConnetctTcp.Remove(tcpClient.Token); } }, ex => { EasyOp.Do(tcpClient.SafeClose); LogUtils.Debug($"建立隧道失败,无法连接服务器:token:{tcpClient.Token} {item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}."); }); } else { LogUtils.Debug($"建立隧道失败:未连接到服务器!"); socket.Close(); } } catch (Exception ex) { LogUtils.Debug("处理新tcp连接时发生错误:" + Environment.NewLine + ex.ToString()); } }
/// <summary> /// 管道数据读取回调方法 /// </summary> /// <param name="ar"></param> protected override void ReadCallBack(IAsyncResult ar) { PipeSt st = ar.AsyncState as PipeSt; int length = st.pipe.EndRead(ar); if (length > 0) { st.pipe.BeginRead(st.buffer, 0, st.buffer.Length, ReadCallBack, st); string strData = Encoding.Unicode.GetString(st.buffer.Take(length).ToArray()); string[] strSplit = strData.Split(' ').Where(t => !string.IsNullOrWhiteSpace(t)).ToArray(); AppCenter appCenter = EasyInject.Get <AppCenter>(); if (strSplit[0] == "ls") { string msg = "当前监听端口:"; appCenter.Config.PortMapList.ForEach(t => { msg += t.LocalPort + " "; }); WriteLine(st.pipe, msg); } else if (strSplit[0] == "v") { WriteLine(st.pipe, $"当前版本 { EasyInject.Get<AppCenter>().SoftVerSion}"); } else if (strSplit[0] == "use") { IConfig configManager = EasyInject.Get <IConfig>(); EasyOp.Do(() => { PortMapItem obj = configManager.ParseToObject("[PortMapItem]", strSplit[1]) as PortMapItem; if (obj != null) { //设置配置文件更新时间,避免出发重加载配置文件逻辑 appCenter.LastUpdateConfig = DateTime.Now; //添加/修改指定项到配置文件 configManager.SaveItem(obj); P2PClient client = EasyInject.Get <P2PClient>(); //监听/修改端口映射 if (client.UsePortMapItem(obj)) { appCenter.Config.PortMapList.Add(obj); WriteLine(st.pipe, "添加/修改端口映射成功!"); LogUtils.Info($"管道命令:添加/修改端口映射 {obj.LocalPort}->{obj.RemoteAddress}:{obj.RemotePort}"); } else { WriteLine(st.pipe, "添加/修改端口映射失败,请参考wiki中的端口映射配置项!"); } } else { WriteLine(st.pipe, "添加/修改端口映射失败,请参考wiki中的端口映射配置项!"); } }, e => { WriteLine(st.pipe, $"添加/修改端口映射异常:{e}"); }); } else if (strSplit[0] == "del") { int localPort; if (int.TryParse(strSplit[1], out localPort)) { EasyOp.Do(() => { //设置配置文件更新时间,避免出发重加载配置文件逻辑 appCenter.LastUpdateConfig = DateTime.Now; P2PClient client = EasyInject.Get <P2PClient>(); //停止监听端口 client.UnUsePortMapItem(localPort); IConfig configManager = EasyInject.Get <IConfig>(); //移除配置文件中指定项 configManager.RemoveItem(new PortMapItem() { LocalPort = localPort }); WriteLine(st.pipe, "移除端口映射成功!"); LogUtils.Info($"管道命令:移除端口映射 {localPort}"); }, e => { WriteLine(st.pipe, $"移除端口映射异常:{e}"); }); } else { WriteLine(st.pipe, "移除端口映射失败!"); } } else if (strSplit[0] == "log") { if (strSplit.Length == 2 && strSplit[1] == "-s") { LogItem pipeSt = logItems.FirstOrDefault(t => t.item == st.pipe); logItems.Remove(pipeSt); WriteLine(st.pipe, "停止记录日志"); } else { LogLevel level = appCenter.Config.LogLevel; if (strSplit.Length == 2) { switch (strSplit[1].ToLower()) { case "debug": level = LogLevel.Debug; break; case "error": level = LogLevel.Error; break; case "info": level = LogLevel.Info; break; case "none": level = LogLevel.None; break; case "warning": level = LogLevel.Warning; break; case "trace": level = LogLevel.Trace; break; } } if (!logItems.Any(t => t.item == st.pipe)) { LogItem item = new LogItem(); item.item = st.pipe; item.level = level; logItems.Add(item); WriteLine(st.pipe, $"开始记录日志,级别:{level}"); } else { LogItem pipeSt = logItems.FirstOrDefault(t => t.item == st.pipe); pipeSt.level = level; WriteLine(st.pipe, $"设置日志级别:{level}"); } } } else if (strSplit[0] == "h") { string msg = ""; using (MemoryStream ms = new MemoryStream()) { StreamWriter writer = new StreamWriter(ms); writer.WriteLine("1.开始日志打印: log [Debug/Info/Warning/Trace]"); writer.WriteLine("2.结束日志打印: log -s"); writer.WriteLine("3.获取监听端口: ls"); writer.WriteLine("4.获取当前版本: v"); writer.WriteLine("5.添加/修改端口映射: use 映射配置 (例:\"use 12345->[ClientA]:3389\")"); writer.WriteLine("6.删除指定端口映射: del 端口号 (例:\"del 3388\")"); writer.Close(); msg = Encoding.UTF8.GetString(ms.ToArray()); } WriteLine(st.pipe, msg); } else { WriteLine(st.pipe, "暂不支持此命令,输入\"h\"查看帮助"); } } }
public void P2PBind_DirectConnect(P2PTcpClient p2pClient, string token) { if (m_tcpClient.P2PLocalPort > 0) { //B端 int port = m_tcpClient.P2PLocalPort; PortMapItem destMap = appCenter.PortMapList.FirstOrDefault(t => t.LocalPort == port && string.IsNullOrEmpty(t.LocalAddress)); P2PTcpClient portClient = null; EasyOp.Do(() => { if (destMap != null) { if (destMap.MapType == PortMapType.ip) { portClient = new P2PTcpClient(destMap.RemoteAddress, destMap.RemotePort); } else { portClient = new P2PTcpClient("127.0.0.1", port); } } else { portClient = new P2PTcpClient("127.0.0.1", port); } }, () => { portClient.IsAuth = p2pClient.IsAuth = true; portClient.ToClient = p2pClient; p2pClient.ToClient = portClient; EasyOp.Do(() => { if (Global_Func.BindTcp(p2pClient, portClient)) { LogUtils.Debug($"命令:0x0201 P2P模式隧道,连接成功 token:{token}"); } else { LogUtils.Debug($"命令:0x0201 P2P模式隧道,连接失败 token:{token}"); } }, ex => { LogUtils.Debug($"命令:0x0201 P2P模式隧道,连接失败 token:{token}:{Environment.NewLine}{ex}"); }); }, ex => { LogUtils.Debug($"命令:0x0201 P2P模式隧道,连接目标端口失败 token:{token}:{Environment.NewLine}{ex}"); EasyOp.Do(p2pClient.SafeClose); }); } else { //A端,发起端 if (tcpCenter.WaiteConnetctTcp.ContainsKey(token)) { P2PTcpClient portClient = tcpCenter.WaiteConnetctTcp[token]; tcpCenter.WaiteConnetctTcp.Remove(token); portClient.IsAuth = p2pClient.IsAuth = true; portClient.ToClient = p2pClient; p2pClient.ToClient = portClient; EasyOp.Do(() => { if (Global_Func.BindTcp(p2pClient, portClient)) { LogUtils.Debug($"命令:0x0201 P2P模式隧道,连接成功 token:{token}"); } else { LogUtils.Debug($"命令:0x0201 P2P模式隧道,连接失败 token:{token}"); } }, ex => { LogUtils.Debug($"命令:0x0201 P2P模式隧道,连接失败 token:{token}:{Environment.NewLine}{ex}"); }); } else { LogUtils.Debug($"命令:0x0201 接收到建立隧道命令,但已超时. token:{token}"); EasyOp.Do(p2pClient.SafeClose); } } }
/// <summary> /// 端口映射监听端口的新tcp回调方法 /// </summary> /// <param name="ar"></param> public void AcceptSocket_Server(IAsyncResult ar) { ListenSt st = (ListenSt)ar.AsyncState; TcpListener listener = st.listener; PortMapItem item = st.item; Socket socket = null; try { //获取当前接入的tcp socket = listener.EndAcceptSocket(ar); } catch (Exception ex) { LogUtils.Error(ex.ToString()); return; } EasyOp.Do(() => { listener.BeginAcceptSocket(AcceptSocket_Server, st); }, () => { EasyOp.Do(() => { if (tcpCenter.P2PServerTcp != null && tcpCenter.P2PServerTcp.Connected) { P2PTcpClient tcpClient = new P2PTcpClient(socket); //加入待连接集合 P2PResult result = new P2PResult(); tcpCenter.WaiteConnetctTcp.Add(tcpClient.Token, result); //tcpCenter.WaiteConnetctTcp.Add(tcpClient.Token, tcpClient); //发送消息给服务端,开始内网穿透 Send_0x0201_Apply packet = new Send_0x0201_Apply(tcpClient.Token, item.RemoteAddress, item.RemotePort, item.P2PType); LogUtils.Debug(string.Format("正在建立{0}隧道 token:{1} client:{2} port:{3}", item.P2PType == 0 ? "中转模式" : "P2P模式", tcpClient.Token, item.RemoteAddress, item.RemotePort)); byte[] dataAr = packet.PackData(); EasyOp.Do(() => { tcpCenter.P2PServerTcp.BeginSend(dataAr); }, () => { //等待指定超时时间后,判断是否连接成功 Monitor.Enter(result.block); if (Monitor.Wait(result.block, AppConfig.P2PTimeout)) { if (tcpCenter.WaiteConnetctTcp[tcpClient.Token].IsError) { LogUtils.Debug(tcpCenter.WaiteConnetctTcp[tcpClient.Token].ErrorMsg); tcpClient.SafeClose(); } else { P2PTcpClient destTcp = tcpCenter.WaiteConnetctTcp[tcpClient.Token].Tcp; tcpClient.IsAuth = destTcp.IsAuth = true; destTcp.ToClient = tcpClient; tcpClient.ToClient = destTcp; if (item.P2PType == 0) { Global_Func.ListenTcp <Packet_0x0202>(tcpClient); LogUtils.Debug($"中转模式隧道,连接成功 token:{tcpClient.Token}"); } else { if (Global_Func.BindTcp(tcpClient, destTcp)) { LogUtils.Debug($"P2P模式隧道,连接成功 token:{tcpClient.Token}"); } else { LogUtils.Debug($"P2P模式隧道,连接失败 token:{tcpClient.Token}"); EasyOp.Do(tcpClient.SafeClose); EasyOp.Do(destTcp.SafeClose); } } } } else { LogUtils.Debug($"建立隧道失败:token:{tcpClient.Token} {item.LocalPort}->{item.RemoteAddress}:{item.RemotePort} {AppConfig.P2PTimeout / 1000}秒无响应,已超时."); EasyOp.Do(tcpClient.SafeClose); } tcpCenter.WaiteConnetctTcp.Remove(tcpClient.Token); Monitor.Exit(result.block); //if (tcpCenter.WaiteConnetctTcp.ContainsKey(tcpClient.Token)) //{ // LogUtils.Debug($"建立隧道失败:token:{tcpClient.Token} {item.LocalPort}->{item.RemoteAddress}:{item.RemotePort} {AppConfig.P2PTimeout / 1000}秒无响应,已超时."); // tcpCenter.WaiteConnetctTcp[tcpClient.Token].tcp?.SafeClose(); // tcpCenter.WaiteConnetctTcp.Remove(tcpClient.Token); //} }, ex => { EasyOp.Do(tcpClient.SafeClose); LogUtils.Debug($"建立隧道失败,无法连接服务器:token:{tcpClient.Token} {item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}."); }); } else { LogUtils.Debug($"建立隧道失败:未连接到服务器!"); socket.Close(); } }, ex => { LogUtils.Debug("处理新tcp连接时发生错误:" + Environment.NewLine + ex.ToString()); }); }, ex => { LogUtils.Error("监听端口发生错误:" + listener.LocalEndpoint.ToString() + Environment.NewLine + ex.ToString()); }); }
/// <summary> /// 从目标端创建与服务器的tcp连接 /// </summary> /// <param name="token"></param> public void CreateTcpFromDest(string token) { Utils.LogUtils.Debug($"命令:0x0201 正在连接中转模式隧道通道 token:{token}"); int port = BinaryUtils.ReadInt(data); PortMapItem destMap = appCenter.PortMapList.FirstOrDefault(t => t.LocalPort == port && string.IsNullOrEmpty(t.LocalAddress)); P2PTcpClient portClient = null; EasyOp.Do(() => { if (destMap != null) { if (destMap.MapType == PortMapType.ip) { portClient = new P2PTcpClient(destMap.RemoteAddress, destMap.RemotePort); } else { portClient = new P2PTcpClient("127.0.0.1", port); } } else { portClient = new P2PTcpClient("127.0.0.1", port); } }, () => { P2PTcpClient serverClient = null; EasyOp.Do(() => { serverClient = new P2PTcpClient(appCenter.ServerAddress, appCenter.ServerPort); }, () => { portClient.IsAuth = serverClient.IsAuth = true; portClient.ToClient = serverClient; serverClient.ToClient = portClient; Models.Send.Send_0x0201_Bind sendPacket = new Models.Send.Send_0x0201_Bind(token); EasyOp.Do(() => { serverClient.BeginSend(sendPacket.PackData()); }, () => { EasyOp.Do(() => { Global_Func.ListenTcp <ReceivePacket>(serverClient); Utils.LogUtils.Debug($"命令:0x0201 中转模式隧道,连接成功 token:{token}"); }, ex => { LogUtils.Debug($"命令:0x0201 P2P模式隧道,连接失败 token:{token}:{Environment.NewLine}{ex}"); EasyOp.Do(portClient.SafeClose); EasyOp.Do(portClient.SafeClose); }); }, ex => { LogUtils.Debug($"命令:0x0201 P2P模式隧道,连接失败 token:{token}:{Environment.NewLine}{ex}"); EasyOp.Do(portClient.SafeClose); }); }, ex => { LogUtils.Debug($"命令:0x0201 P2P模式隧道,连接失败 token:{token}:{Environment.NewLine}{ex}"); EasyOp.Do(portClient.SafeClose); }); }, ex => { LogUtils.Debug($"命令:0x0201 P2P模式隧道,连接目标端口失败 token{token}:{Environment.NewLine}{ex}"); }); }
public void AcceptSocket_ClientName(IAsyncResult ar) { ListenSt st = (ListenSt)ar.AsyncState; TcpListener listener = st.listener; PortMapItem item = st.item; Socket socket = null; EasyOp.Do(() => { socket = listener.EndAcceptSocket(ar); }, () => { EasyOp.Do(() => { listener.BeginAcceptSocket(AcceptSocket_ClientName, st); }, exx => { LogUtils.Error($"端口监听失败:{Environment.NewLine}{exx}"); }); LogUtils.Debug($"开始内网穿透:{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}", false); P2PTcpClient tcpClient = null; EasyOp.Do(() => { tcpClient = new P2PTcpClient(socket); }, () => { string token = tcpClient.Token; //获取目标tcp if (clientCenter.TcpMap.ContainsKey(item.RemoteAddress) && clientCenter.TcpMap[item.RemoteAddress].TcpClient.Connected) { //加入待连接集合 clientCenter.WaiteConnetctTcp.Add(token, tcpClient); //发送p2p申请 Models.Send.Send_0x0211 packet = new Models.Send.Send_0x0211(token, item.RemotePort, tcpClient.RemoteEndPoint); EasyOp.Do(() => { clientCenter.TcpMap[item.RemoteAddress].TcpClient.BeginSend(packet.PackData()); }, () => { Thread.Sleep(appCenter.Config.P2PTimeout); //如果指定时间内没有匹配成功,则关闭连接 if (clientCenter.WaiteConnetctTcp.ContainsKey(token)) { LogUtils.Debug($"建立隧道失败{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort},{appCenter.Config.P2PTimeout / 1000}秒无响应,已超时."); EasyOp.Do(() => tcpClient?.SafeClose()); EasyOp.Do(() => clientCenter.WaiteConnetctTcp[token]?.SafeClose()); clientCenter.WaiteConnetctTcp.Remove(token); } }, ex => { LogUtils.Debug($"建立隧道失败{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort},目标客户端已断开连接!"); EasyOp.Do(() => tcpClient?.SafeClose()); if (clientCenter.WaiteConnetctTcp.ContainsKey(token)) { EasyOp.Do(() => clientCenter.WaiteConnetctTcp[token]?.SafeClose()); clientCenter.WaiteConnetctTcp.Remove(token); } }); } else { LogUtils.Debug($"建立隧道失败{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort},客户端不在线!"); EasyOp.Do(() => tcpClient?.SafeClose()); } }, ex => { LogUtils.Debug($"处理新接入Tcp时发生错误:{Environment.NewLine}{ex}"); EasyOp.Do(() => socket?.SafeClose()); }); }, ex => { LogUtils.Debug($"获取新接入的Tcp连接失败:{Environment.NewLine}{ex}"); EasyOp.Do(() => { listener.BeginAcceptSocket(AcceptSocket_ClientName, st); }, exx => { LogUtils.Error($"端口监听失败:{Environment.NewLine}{exx}"); }); }); }