Beispiel #1
0
        public void P2PBind_DirectConnect(string token)
        {
            P2PTcpClient clientA = clientCenter.WaiteConnetctTcp[token];
            P2PTcpClient clientB = m_tcpClient;

            Send_0x0201_Success sendPacketA = new Send_0x0201_Success(14);

            sendPacketA.WriteDirectData(clientB.Client.RemoteEndPoint.ToString(), token);
            Send_0x0201_Success sendPacketB = new Send_0x0201_Success(14);

            sendPacketB.WriteDirectData(clientA.Client.RemoteEndPoint.ToString(), token);

            EasyOp.Do(() => clientA.BeginSend(sendPacketA.PackData()));
            EasyOp.Do(() => clientB.BeginSend(sendPacketB.PackData()));

            EasyOp.Do(() => clientA?.SafeClose());
            EasyOp.Do(() => clientB?.SafeClose());
        }
Beispiel #2
0
        public static void ListenTcp <T>(P2PTcpClient tcpClient) where T : ReceivePacket
        {
            RelationTcp_Server relationSt = new RelationTcp_Server();

            relationSt.buffer     = new byte[P2PGlobal.P2PSocketBufferSize];
            relationSt.readTcp    = tcpClient;
            relationSt.msgReceive = Activator.CreateInstance(typeof(T)) as ReceivePacket;
            relationSt.guid       = EasyInject.Get <AppCenter>().CurrentGuid;
            relationSt.readTcp.GetStream().BeginRead(relationSt.buffer, 0, relationSt.buffer.Length, ReadTcp_Server, relationSt);
            //如果20秒仍未授权,则关闭
            TimerUtils.Instance.AddJob(() =>
            {
                if (!tcpClient.IsAuth)
                {
                    EasyOp.Do(() => tcpClient?.SafeClose());
                }
            }, 20000);
        }
        public static bool BindTcp(P2PTcpClient readTcp, P2PTcpClient toTcp)
        {
            //TcpCenter.Instance.ConnectedTcpList.Add(readTcp);
            //TcpCenter.Instance.ConnectedTcpList.Add(toTcp);
            bool           ret        = true;
            RelationTcp_Ip toRelation = new RelationTcp_Ip();

            EasyOp.Do(() =>
            {
                toRelation.readTcp  = readTcp;
                toRelation.readSs   = readTcp.GetStream();
                toRelation.writeTcp = toTcp;
                toRelation.writeSs  = toTcp.GetStream();
                toRelation.buffer   = new byte[P2PGlobal.P2PSocketBufferSize];
                StartTransferTcp_Ip(toRelation);
            },
                      () =>
            {
                EasyOp.Do(() =>
                {
                    RelationTcp_Ip fromRelation = new RelationTcp_Ip();
                    fromRelation.readTcp        = toRelation.writeTcp;
                    fromRelation.readSs         = toRelation.writeSs;
                    fromRelation.writeTcp       = toRelation.readTcp;
                    fromRelation.writeSs        = toRelation.readSs;
                    fromRelation.buffer         = new byte[P2PGlobal.P2PSocketBufferSize];
                    StartTransferTcp_Ip(fromRelation);
                },
                          ex =>
                {
                    LogUtils.Debug($"绑定Tcp失败:{Environment.NewLine}{ex}");
                    EasyOp.Do(readTcp.SafeClose);
                    ret = false;
                });
            },
                      ex =>
            {
                LogUtils.Debug($"绑定Tcp失败:{Environment.NewLine}{ex}");
                EasyOp.Do(readTcp.SafeClose);
                EasyOp.Do(toTcp.SafeClose);
                ret = false;
            });
            return(ret);
        }
Beispiel #4
0
        public void CreateTcpFromDest_DirectConnect(string token)
        {
            int port = BinaryUtils.ReadInt(data);

            Utils.LogUtils.Debug($"命令:0x0201  正尝试建立P2P模式隧道 token:{token}");
            P2PTcpClient serverClient = new P2PTcpClient();

            serverClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

            EasyOp.Do(() =>
            {
                serverClient.Connect(appCenter.ServerAddress, appCenter.ServerPort);
            },
                      () =>
            {
                serverClient.IsAuth       = true;
                serverClient.P2PLocalPort = port;
                serverClient.UpdateEndPoint();
                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);
                        LogUtils.Debug($"命令:0x0201 P2P模式隧道,已连接到服务器,等待下一步操作 token:{token}");
                    }, ex =>
                    {
                        LogUtils.Debug($"命令:0x0201 P2P模式隧道,服务器连接被强制断开 token:{token}:{Environment.NewLine}{ex}");
                        EasyOp.Do(serverClient.Close);
                    });
                }, ex =>
                {
                    LogUtils.Debug($"命令:0x0201 P2P模式隧道,隧道打洞失败 token:{token}:{Environment.NewLine} 隧道被服务器强制断开");
                });
            }, ex =>
            {
                LogUtils.Debug($"命令:0x0201 P2P模式隧道,无法连接服务器 token:{token}:{Environment.NewLine}{ex}");
            });
        }
 /// <summary>
 ///     监听映射端口并转发数据(ip直接转发模式)
 /// </summary>
 /// <param name="readClient"></param>
 private void ListenPortMapTcpWithIp(P2PTcpClient readClient)
 {
     if (readClient.ToClient == null || !readClient.ToClient.Connected)
     {
         LogUtils.Warning($"数据转发(ip模式)失败:绑定的Tcp连接已断开.");
         readClient.SafeClose();
         return;
     }
     TcpCenter.Instance.ConnectedTcpList.Add(readClient);
     byte[] buffer = new byte[P2PGlobal.P2PSocketBufferSize];
     try
     {
         NetworkStream readStream = readClient.GetStream();
         NetworkStream toStream   = readClient.ToClient.GetStream();
         while (readClient.Connected)
         {
             int curReadLength = readStream.ReadSafe(buffer, 0, buffer.Length);
             if (curReadLength > 0)
             {
                 toStream.Write(buffer, 0, curReadLength);
             }
             else
             {
                 LogUtils.Warning($"端口映射转发(ip模式):源Tcp连接已断开.");
                 //如果tcp已关闭,需要关闭相关tcp
                 try
                 {
                     readClient.ToClient.SafeClose();
                 }
                 finally
                 {
                 }
                 break;
             }
         }
     }
     catch (Exception ex)
     {
         LogUtils.Warning($"端口映射转发(ip模式):目标Tcp连接已断开.");
         readClient.SafeClose();
     }
     TcpCenter.Instance.ConnectedTcpList.Remove(readClient);
 }
Beispiel #6
0
 /// <summary>
 ///     从发起端创建与服务器的tcp连接
 /// </summary>
 /// <param name="token"></param>
 protected virtual void CreateTcpFromSource(string token)
 {
     Utils.LogUtils.Debug($"命令:0x0201  正尝试建立中转模式隧道token:{token}");
     if (tcpCenter.WaiteConnetctTcp.ContainsKey(token))
     {
         P2PTcpClient serverClient = null;
         EasyOp.Do(() =>
         {
             serverClient = new P2PTcpClient(appCenter.ServerAddress, appCenter.ServerPort);
         }, () =>
         {
             Models.Send.Send_0x0201_Bind sendPacket = new Models.Send.Send_0x0201_Bind(token);
             EasyOp.Do(() =>
             {
                 serverClient.BeginSend(sendPacket.PackData());
             }, () =>
             {
                 EasyOp.Do(() =>
                 {
                     tcpCenter.WaiteConnetctTcp[token].Tcp = serverClient;
                     Global_Func.ListenTcp <ReceivePacket>(serverClient);
                     //Utils.LogUtils.Debug($"命令:0x0201  中转模式隧道,隧道建立并连接成功 token:{token}");
                 }, ex =>
                 {
                     tcpCenter.WaiteConnetctTcp[token].ErrorMsg = $"命令:0x0201  中转模式隧道,隧道建立失败 token:{token}:{Environment.NewLine} {ex}";
                     tcpCenter.WaiteConnetctTcp[token].PulseBlock();
                 });
             }, ex =>
             {
                 tcpCenter.WaiteConnetctTcp[token].ErrorMsg = $"命令:0x0201  中转模式隧道,隧道建立失败 token:{token}:{Environment.NewLine} 隧道被服务器强制断开";
                 tcpCenter.WaiteConnetctTcp[token].PulseBlock();
             });
         }, ex =>
         {
             tcpCenter.WaiteConnetctTcp[token].ErrorMsg = $"命令:0x0201  中转模式隧道,无法连接服务器 token:{token}:{Environment.NewLine}{ex}";
             tcpCenter.WaiteConnetctTcp[token].PulseBlock();
         });
     }
     else
     {
         LogUtils.Debug($"命令:0x0201 接收到建立中转模式隧道命令,但已超时. token:{token}");
     }
 }
 public void CreateTcpFromSource_DirectConnect(string token)
 {
     Models.Send.Send_0x0201_Bind sendPacket = new Models.Send.Send_0x0201_Bind(token);
     Utils.LogUtils.Info($"命令:0x0201  正尝试内网穿透(P2P模式)token:{token}");
     if (TcpCenter.Instance.WaiteConnetctTcp.ContainsKey(token))
     {
         P2PTcpClient serverClient = new P2PTcpClient();
         serverClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
         serverClient.Connect(ConfigCenter.Instance.ServerAddress, ConfigCenter.Instance.ServerPort);
         serverClient.IsAuth = true;
         serverClient.UpdateEndPoint();
         serverClient.Client.Send(sendPacket.PackData());
         AppCenter.Instance.StartNewTask(() => { Global_Func.ListenTcp <ReceivePacket>(serverClient); });
     }
     else
     {
         LogUtils.Warning($"命令:0x0201 接收到内网穿透(P2P模式)命令,但已超时. token:{token}");
     }
 }
        /// <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 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));
                        }
                    });
                }
            });
        }
Beispiel #10
0
 /// <summary>
 ///     从发起端创建与服务器的tcp连接
 /// </summary>
 /// <param name="token"></param>
 public void CreateTcpFromSource(string token)
 {
     Models.Send.Send_0x0201_Bind sendPacket = new Models.Send.Send_0x0201_Bind(token);
     if (Global.WaiteConnetctTcp.ContainsKey(token))
     {
         P2PTcpClient portClient = Global.WaiteConnetctTcp[token];
         Global.WaiteConnetctTcp.Remove(token);
         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); });
     }
     else
     {
         LogUtils.Warning($"【P2P】命令:0x0201 接收到P2P命令,但已超时.");
     }
 }
Beispiel #11
0
        protected virtual P2PTcpClient TryRadomPort(string ip, int port)
        {
            P2PTcpClient  ret    = null;
            AsyncCallback action = ar =>
            {
                P2PTcpClient tcp = ar.AsyncState as P2PTcpClient;
                EasyOp.Do(() => tcp.EndConnect(ar), () =>
                {
                    if (tcp != null && tcp.Connected)
                    {
                        ret = tcp;
                    }
                }, ex =>
                {
                    LogUtils.Trace($"{ex.Message}");
                });
            };
            List <P2PTcpClient> tcpList = new List <P2PTcpClient>();

            for (int i = 1; i <= 8; i++)
            {
                P2PTcpClient tcp = new P2PTcpClient();
                tcpList.Add(tcp);
                tcp.BeginConnect(ip, port + 6, action, tcp);
            }
            int cTime = 0;

            while (ret == null && cTime < 3000)
            {
                Thread.Sleep(100);
                cTime += 100;
            }
            tcpList.ForEach(t =>
            {
                if (t != ret)
                {
                    EasyOp.Do(() => t.Close());
                    EasyOp.Do(() => t.Dispose());
                }
            });
            return(ret);
        }
 /// <summary>
 ///     从发起端创建与服务器的tcp连接
 /// </summary>
 /// <param name="token"></param>
 public void CreateTcpFromSource(string token)
 {
     Models.Send.Send_0x0201_Bind sendPacket = new Models.Send.Send_0x0201_Bind(token);
     Utils.LogUtils.Info($"命令:0x0201  正尝试内网穿透(转发模式)token:{token}");
     if (TcpCenter.Instance.WaiteConnetctTcp.ContainsKey(token))
     {
         P2PTcpClient portClient = TcpCenter.Instance.WaiteConnetctTcp[token];
         TcpCenter.Instance.WaiteConnetctTcp.Remove(token);
         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); });
     }
     else
     {
         LogUtils.Warning($"命令:0x0201 接收到内网穿透(转发模式)命令,但已超时. token:{token}");
     }
 }
Beispiel #13
0
        public static void ListenTcp <T>(P2PTcpClient tcpClient) where T : RecievePacket
        {
            byte[]        buffer     = new byte[P2PGlobal.P2PSocketBufferSize];
            NetworkStream tcpStream  = tcpClient.GetStream();
            RecievePacket msgRecieve = Activator.CreateInstance(typeof(T)) as RecievePacket;

            while (tcpClient.Connected)
            {
                int curReadLength = tcpStream.ReadSafe(buffer, 0, buffer.Length);
                if (curReadLength > 0)
                {
                    byte[] refData = buffer.Take(curReadLength).ToArray();
                    while (msgRecieve.ParseData(ref refData))
                    {
                        Debug.WriteLine($"命令类型:{msgRecieve.CommandType}");
                        //todo:执行command
                        P2PCommand command = FindCommand(tcpClient, msgRecieve);
                        if (command != null)
                        {
                            command.Excute();
                        }
                        //重置msgRecieve
                        msgRecieve = Activator.CreateInstance(typeof(T)) as RecievePacket;
                        if (refData.Length <= 0)
                        {
                            break;
                        }
                    }
                }
                else
                {
                    //如果tcp已关闭,需要关闭相关tcp
                    if (tcpClient.ToClient != null && tcpClient.ToClient.Connected)
                    {
                        Debug.WriteLine("tcp已关闭");
                        tcpClient.ToClient.Close();
                    }
                    break;
                }
            }
        }
 public void CreateTcpFromDest_DirectConnect(string token)
 {
     try
     {
         int port = BinaryUtils.ReadInt(data);
         Models.Send.Send_0x0201_Bind sendPacket = new Models.Send.Send_0x0201_Bind(token);
         Utils.LogUtils.Info($"命令:0x0201  正尝试内网穿透(P2P模式) token:{token}");
         P2PTcpClient serverClient = new P2PTcpClient();
         serverClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
         serverClient.Connect(ConfigCenter.Instance.ServerAddress, ConfigCenter.Instance.ServerPort);
         serverClient.IsAuth       = true;
         serverClient.P2PLocalPort = port;
         serverClient.UpdateEndPoint();
         serverClient.Client.Send(sendPacket.PackData());
         AppCenter.Instance.StartNewTask(() => { Global_Func.ListenTcp <ReceivePacket>(serverClient); });
     }
     catch (Exception ex)
     {
         LogUtils.Error($"命令:0x0201 尝试内网穿透(P2P模式) 发生错误:{Environment.NewLine}{ex.Message}");
     }
 }
Beispiel #15
0
        /// <summary>
        ///     监听映射端口并转发数据(ip直接转发模式)
        /// </summary>
        /// <param name="readClient"></param>
        private void ListenPortMapTcpWithIp(P2PTcpClient readClient)
        {
            if (readClient.ToClient == null || !readClient.ToClient.Connected)
            {
                Debug.WriteLine($"[错误]端口映射:目标tcp不存在");
                readClient.Close();
                return;
            }
            byte[]        buffer     = new byte[P2PGlobal.P2PSocketBufferSize];
            NetworkStream readStream = readClient.GetStream();
            NetworkStream toStream   = readClient.ToClient.GetStream();

            while (readClient.Connected)
            {
                int curReadLength = readStream.ReadSafe(buffer, 0, buffer.Length);
                if (curReadLength > 0)
                {
                    if (readClient.ToClient != null && readClient.ToClient.Connected)
                    {
                        toStream.Write(buffer, 0, curReadLength);
                    }
                    else
                    {
                        Debug.WriteLine($"远程端口已关闭{readClient.Client.RemoteEndPoint}");
                        readClient.Close();
                        break;
                    }
                }
                else
                {
                    Debug.WriteLine($"从端口{readClient.LocalEndPoint}读取到0的数据");
                    //如果tcp已关闭,需要关闭相关tcp
                    if (readClient.ToClient != null && readClient.ToClient.Connected)
                    {
                        readClient.ToClient.Close();
                    }
                    break;
                }
            }
        }
        /// <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>
        ///     监听映射端口并转发数据(ip直接转发模式)
        /// </summary>
        /// <param name="readClient"></param>
        private void ListenPortMapTcpWithIp(P2PTcpClient readClient)
        {
            if (readClient.ToClient == null || !readClient.ToClient.Connected)
            {
                LogUtils.Warning($"【失败】IP数据转发:绑定的Tcp连接已断开.");
                readClient.Close();
                return;
            }
            byte[]        buffer     = new byte[P2PGlobal.P2PSocketBufferSize];
            NetworkStream readStream = readClient.GetStream();
            NetworkStream toStream   = readClient.ToClient.GetStream();

            while (readClient.Connected)
            {
                int curReadLength = readStream.ReadSafe(buffer, 0, buffer.Length);
                if (curReadLength > 0)
                {
                    if (readClient.ToClient != null && readClient.ToClient.Connected)
                    {
                        toStream.Write(buffer, 0, curReadLength);
                    }
                    else
                    {
                        LogUtils.Warning($"【失败】IP数据转发:目标Tcp连接已断开.");
                        readClient.Close();
                        break;
                    }
                }
                else
                {
                    LogUtils.Warning($"【失败】IP数据转发:Tcp连接已断开.");
                    //如果tcp已关闭,需要关闭相关tcp
                    if (readClient.ToClient != null && readClient.ToClient.Connected)
                    {
                        readClient.ToClient.Close();
                    }
                    break;
                }
            }
        }
Beispiel #18
0
        /// <summary>
        ///     监听消息端口
        /// </summary>
        private void ListenMessagePort()
        {
            //服务端口限制在1000以上
            if (Global.LocalPort > 1000)
            {
                try
                {
                    TcpListener listener = new TcpListener(IPAddress.Any, Global.LocalPort);
                    listener.Start();
                    ConsoleUtils.Write($"开始监听{Global.LocalPort}端口.");

                    Global.TaskFactory.StartNew(() =>
                    {
                        try
                        {
                            while (true)
                            {
                                Socket socket          = listener.AcceptSocket();
                                P2PTcpClient tcpClient = new P2PTcpClient(socket);
                                //接收数据
                                Global.TaskFactory.StartNew(() =>
                                {
                                    Global_Func.ListenTcp <RecievePacket>(tcpClient);
                                });
                                var endPoint = socket.RemoteEndPoint as IPEndPoint;
                                ConsoleUtils.Write($"已连接客户端{endPoint.Address.ToString()}:{endPoint.Port}");
                            }
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine(ex.Message);
                        }
                    });
                }
                catch
                {
                    ConsoleUtils.Write($"端口{Global.LocalPort}监听失败.");
                }
            }
        }
 private void ConnectServer()
 {
     try
     {
         P2PTcpClient p2PTcpClient = new P2PTcpClient(Global.ServerAddress, Global.ServerPort);
         ConsoleUtils.Write($"服务器{Global.ServerAddress}:{Global.ServerPort}连接成功.");
         p2PTcpClient.IsAuth = true;
         Global.P2PServerTcp = p2PTcpClient;
         //接收数据
         Global.TaskFactory.StartNew(() =>
         {
             //向服务器发送客户端信息
             InitServerInfo(p2PTcpClient);
             //监听来自服务器的消息
             Global_Func.ListenTcp <RecievePacket>(p2PTcpClient);
         });
     }
     catch
     {
         ConsoleUtils.Write($"服务器{Global.ServerAddress}:{Global.ServerPort}连接失败!");
     }
 }
Beispiel #20
0
        /// <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()}");
            }
        }
Beispiel #21
0
 private void ConnectServer()
 {
     try
     {
         P2PTcpClient p2PTcpClient = new P2PTcpClient(Global.ServerAddress, Global.ServerPort);
         LogUtils.Show($"{DateTime.Now.ToString("【成功】[HH:mm:ss]")}连接服务器:{Global.ServerAddress}:{Global.ServerPort}");
         p2PTcpClient.IsAuth = true;
         Global.P2PServerTcp = p2PTcpClient;
         //接收数据
         Global.TaskFactory.StartNew(() =>
         {
             //向服务器发送客户端信息
             InitServerInfo(p2PTcpClient);
             //监听来自服务器的消息
             Global_Func.ListenTcp <ReceivePacket>(p2PTcpClient);
         });
     }
     catch
     {
         LogUtils.Error($"{DateTime.Now.ToString("【失败】[HH:mm:ss]")}连接服务器:{Global.ServerAddress}:{Global.ServerPort}");
     }
 }
        public static void BindTcp(P2PTcpClient readTcp, P2PTcpClient toTcp)
        {
            TcpCenter.Instance.ConnectedTcpList.Add(readTcp);
            byte[]        buffer     = new byte[P2PGlobal.P2PSocketBufferSize];
            NetworkStream readStream = readTcp.GetStream();
            NetworkStream toStream   = toTcp.GetStream();

            while (readTcp.Connected)
            {
                int curReadLength = readStream.ReadSafe(buffer, 0, buffer.Length);
                if (curReadLength > 0)
                {
                    bool isError = true;
                    if (toTcp != null && toTcp.Connected)
                    {
                        try
                        {
                            toStream.Write(buffer, 0, curReadLength);
                            isError = false;
                        }
                        catch { }
                    }
                    if (isError)
                    {
                        LogUtils.Warning($"Tcp连接{toTcp.RemoteEndPoint}已断开.");
                        readTcp.SafeClose();
                        break;
                    }
                }
                else
                {
                    LogUtils.Warning($"Tcp连接{readTcp.RemoteEndPoint}已断开.");
                    //如果tcp已关闭,需要关闭相关tcp
                    toTcp?.SafeClose();
                    break;
                }
            }
            TcpCenter.Instance.ConnectedTcpList.Remove(readTcp);
        }
        public void P2PBind_DirectConnect(string token)
        {
            P2PTcpClient clientA = ClientCenter.Instance.WaiteConnetctTcp[token];
            P2PTcpClient clientB = m_tcpClient;

            Send_0x0201_Success sendPacketA = new Send_0x0201_Success(14);

            sendPacketA.WriteDirectData(clientB.Client.RemoteEndPoint.ToString(), token);
            Send_0x0201_Success sendPacketB = new Send_0x0201_Success(14);

            sendPacketB.WriteDirectData(clientA.Client.RemoteEndPoint.ToString(), token);

            clientA.Client.Send(sendPacketA.PackData());
            clientB.Client.Send(sendPacketB.PackData());

            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(5000);
                clientA.SafeClose();
                clientB.SafeClose();
            });
        }
Beispiel #24
0
        public override bool Excute()
        {
            int    tokenLength = m_data.ReadInt32();
            string token       = m_data.ReadBytes(tokenLength).ToStringUnicode();

            if (ClientCenter.Instance.WaiteConnetctTcp.ContainsKey(token))
            {
                P2PTcpClient client = ClientCenter.Instance.WaiteConnetctTcp[token];
                ClientCenter.Instance.WaiteConnetctTcp.Remove(token);
                client.IsAuth        = m_tcpClient.IsAuth = true;
                client.ToClient      = m_tcpClient;
                m_tcpClient.ToClient = client;
                LogUtils.Debug($"命令:0x0211 已绑定内网穿透(2端)通道 {client.RemoteEndPoint}->{m_tcpClient.RemoteEndPoint}");
                //监听client
                AppCenter.Instance.StartNewTask(() => { Global_Func.ListenTcp <Packet_0x0212>(client); });
            }
            else
            {
                m_tcpClient.SafeClose();
                throw new Exception("绑定内网穿透(2端)通道失败,目标Tcp连接已断开");
            }
            return(true);
        }
        public override bool Excute()
        {
            int    tokenLength = m_data.ReadInt32();
            string token       = m_data.ReadBytes(tokenLength).ToStringUnicode();

            if (Global.WaiteConnetctTcp.ContainsKey(token))
            {
                P2PTcpClient client = Global.WaiteConnetctTcp[token];
                Global.WaiteConnetctTcp.Remove(token);
                client.IsAuth        = m_tcpClient.IsAuth = true;
                client.ToClient      = m_tcpClient;
                m_tcpClient.ToClient = client;
                Debug.WriteLine($"[服务器]转发{client.RemoteEndPoint}->{m_tcpClient.RemoteEndPoint}");
                //监听client
                Global.TaskFactory.StartNew(() => { Global_Func.ListenTcp <Port2PPacket>(client); });
            }
            else
            {
                m_tcpClient.Close();
                throw new Exception("连接已关闭");
            }
            return(true);
        }
        /// <summary>
        ///     匹配对应的Command命令
        /// </summary>
        /// <param name="tcpClient"></param>
        /// <param name="packet"></param>
        /// <returns></returns>
        public static P2PCommand FindCommand(P2PTcpClient tcpClient, ReceivePacket packet)
        {
            P2PCommand command = null;

            if (EasyInject.Get <AppCenter>().AllowAnonymous.Contains(packet.CommandType) || tcpClient.IsAuth)
            {
                if (EasyInject.Get <AppCenter>().CommandDict.ContainsKey(packet.CommandType))
                {
                    Type type = EasyInject.Get <AppCenter>().CommandDict[packet.CommandType];
                    command = Activator.CreateInstance(type, tcpClient, packet.Data.Select(t => t).ToArray()) as P2PCommand;
                }
                else
                {
                    LogUtils.Warning($"{tcpClient.RemoteEndPoint}请求了未知命令{packet.CommandType}");
                }
            }
            else
            {
                tcpClient?.SafeClose();
                tcpClient.ToClient?.SafeClose();
                LogUtils.Warning($"拦截{tcpClient.RemoteEndPoint}未授权命令");
            }
            return(command);
        }
Beispiel #27
0
 public Cmd_0x0052(P2PTcpClient tcpClient, byte[] data)
 {
     m_tcpClient = tcpClient;
     m_data      = data;
 }
 public Cmd_0x0101(P2PTcpClient tcpClient, byte[] data)
 {
     m_tcpClient = tcpClient;
     m_data      = new BinaryReader(new MemoryStream(data));
 }
 public TokenCommand(P2PTcpClient tcpClient, byte[] data)
 {
     m_tcpClient = tcpClient;
     m_data      = data;
 }
 public Port2PApplyCommand(P2PTcpClient tcpClient, byte[] data)
 {
     m_tcpClient = tcpClient;
     m_data      = new BinaryReader(new MemoryStream(data));
 }