示例#1
0
        public override bool Excute()
        {
            LogUtils.Trace($"开始处理消息:0x0201 From:{m_tcpClient.RemoteEndPoint} Length:{((MemoryStream)m_data.BaseStream).Length}");
            bool ret = true;

            //是否来自端口
            if (BinaryUtils.ReadBool(m_data))
            {
                //Port->Client
                Send_0x0202 sendPacket = new Send_0x0202(BinaryUtils.ReadBytes(m_data), false);
                EasyOp.Do(() => {
                    m_tcpClient.ToClient.BeginSend(sendPacket.PackData());
                }, ex => {
                    LogUtils.Debug($"命令:0x0202 转发来自端口的数据失败:{Environment.NewLine}{ex}");
                    ret = false;
                });
            }
            else
            {
                //Server->Client
                EasyOp.Do(() => {
                    m_tcpClient.ToClient.BeginSend(BinaryUtils.ReadBytes(m_data));
                }, ex => {
                    LogUtils.Debug($"命令:0x0202 转发来自服务器的数据失败:{Environment.NewLine}{ex}");
                    ret = false;
                });
            }
            return(ret);
        }
示例#2
0
        /// <summary>
        ///     监听消息端口
        /// </summary>
        private void ListenMessagePort()
        {
            TcpListener listener = null;

            EasyOp.Do(() =>
            {
                listener = new TcpListener(IPAddress.Any, appCenter.Config.LocalPort);
                listener.Start();
                LogUtils.Info($"监听服务端口:{appCenter.Config.LocalPort}");
            }, () =>
            {
                ListenerList.Add(listener);
                ListenSt listenSt = new ListenSt();
                listenSt.listener = listener;
                EasyOp.Do(() =>
                {
                    listener.BeginAcceptSocket(AcceptSocket_Client, listenSt);
                }, ex =>
                {
                    LogUtils.Error($"监听服务端口发生错误:{Environment.NewLine}{ex}");
                    EasyOp.Do(() => listener.Stop());
                    ListenerList.Remove(listener);
                });
            }, ex =>
            {
                LogUtils.Error($"服务端口监听失败[{appCenter.Config.LocalPort}]:{Environment.NewLine}{ex}");
            });
        }
示例#3
0
        private void TransferTcp_Ip(IAsyncResult ar)
        {
            RelationTcp relation = (RelationTcp)ar.AsyncState;
            int         length   = 0;

            EasyOp.Do(() =>
            {
                length = relation.readTcp.GetStream().EndRead(ar);
            }, () =>
            {
                if (length <= 0 || !EasyOp.Do(() =>
                {
                    relation.writeTcp.BeginSend(relation.buffer.Take(length).ToArray());
                    StartTransferTcp_Ip(relation);
                }))
                {
                    SafeClose(relation.readTcp);
                    SafeClose(relation.writeTcp);
                }
            }, ex =>
            {
                SafeClose(relation.readTcp);
                SafeClose(relation.writeTcp);
            });
        }
示例#4
0
        /// <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}");
            });
        }
        /// <summary>
        /// 加载插件
        /// </summary>
        protected virtual void LoadPlugs()
        {
            string plugPath = Path.Combine(appCenter.RuntimePath, "Plugs");

            if (Directory.Exists(plugPath))
            {
                DirectoryInfo plugDir = new DirectoryInfo(plugPath);
                if (plugDir != null)
                {
                    foreach (string file in plugDir.GetFiles().Select(t => t.FullName).Where(t => t.ToLower().EndsWith(".dll")))
                    {
                        EasyOp.Do(() =>
                        {
                            //载入dll
                            Assembly ab  = Assembly.LoadFrom(file);
                            Type[] types = ab.GetTypes();
                            foreach (Type curInstance in types)
                            {
                                if (curInstance.GetInterface("IP2PSocketPlug") != null)
                                {
                                    IP2PSocketPlug instance = Activator.CreateInstance(curInstance) as IP2PSocketPlug;
                                    LogUtils.Info($"成功加载插件 {instance.GetPlugName()}");
                                    instance.Init();
                                    break;
                                }
                            }
                        },
                                  ex =>
                        {
                            LogUtils.Warning($"加载插件失败 >> {ex}");
                        });
                    }
                }
            }
        }
        public override bool Excute()
        {
            LogUtils.Trace($"开始处理消息:0x0212  From:{m_tcpClient.ToClient.RemoteEndPoint} Length:{((MemoryStream)m_data.BaseStream).Length}");
            bool ret = true;

            if (BinaryUtils.ReadBool(m_data))
            {
                //Port->Client
                Send_0x0212_ToClient sendPacket = new Send_0x0212_ToClient(BinaryUtils.ReadBytes(m_data));
                EasyOp.Do(() => {
                    m_tcpClient.ToClient.BeginSend(sendPacket.PackData());
                }, ex => {
                    LogUtils.Debug($"命令:0x0211 发送数据失败 Port->Server,目标Tcp连接已断开");
                    ret = false;
                });
            }
            else
            {
                //Client->Port
                Send_0x0212_ToPort sendPacket = new Send_0x0212_ToPort(BinaryUtils.ReadBytes(m_data));
                EasyOp.Do(() => {
                    m_tcpClient.ToClient.BeginSend(sendPacket.PackData());
                }, ex => {
                    LogUtils.Debug($"命令:0x0211 发送数据失败 Server->Port,目标Tcp连接已断开");
                    ret = false;
                });
            }
            return(ret);
        }
        public override bool Excute()
        {
            LogUtils.Trace($"开始处理消息:0x0301");
            LogLevel logLevel = BinaryUtils.ReadLogLevel(m_data);
            string   msg      = BinaryUtils.ReadString(m_data);
            string   destName = BinaryUtils.ReadString(m_data);

            if (string.IsNullOrEmpty(destName))
            {
                //  给服务端的消息
                LogUtils.WriteLine(logLevel, msg);
            }
            else
            {
                //  给指定客户端的消息
                if (clientCenter.TcpMap.ContainsKey(destName))
                {
                    //  将消息转发至指定客户端
                    Msg_0x0301 sendPacket = new Msg_0x0301(logLevel, msg, m_tcpClient.ClientName);
                    EasyOp.Do(() => clientCenter.TcpMap[destName].TcpClient.BeginSend(sendPacket.PackData()));
                }
                else
                {
                    //  指定客户端不在线
                    LogUtils.WriteLine(logLevel, $"To_{destName}:{msg}");
                }
            }

            return(true);
        }
示例#8
0
 public object ReadConfig(string text)
 {
     CModel.PortMapItem item = new CModel.PortMapItem();
     EasyOp.Do(() =>
     {
         string curText = text;
         if (ReadLocalIp(ref curText, ref item) &&
             ReadLocalPort(ref curText, ref item) &&
             ReadP2PMode(ref curText, ref item) &&
             ReadRemoteIp(ref curText, ref item) &&
             ReadRemotePort(ref curText, ref item))
         {
             if (!config.PortMapList.Any(t => t.LocalPort == item.LocalPort))
             {
                 config.PortMapList.Add(item);
                 LogDebug($"【PortMapItem配置项】读取成功:{item.LocalAddress}{(item.LocalAddress == "" ? "" : ":")}{item.LocalPort}->{item.RemoteAddress}:{item.RemotePort}");
             }
             else
             {
                 item = null;
                 LogWarning($"【PortMapItem配置项】读取失败:端口{item.LocalPort}已存在映射配置项");
             }
         }
         else
         {
             item = null;
             LogWarning($"【PortMapItem配置项】读取失败:无效的配置项 - {text}");
         }
     }, e =>
     {
         item = null;
         LogWarning($"【PortMapItem配置项】读取失败:无效的配置项 - {text}");
     });
     return(item);
 }
示例#9
0
 /// <summary>
 /// 日志写入响应方法
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void PipeServer_OnWriteLog(object sender, LogInfo e)
 {
     for (int i = logItems.Count - 1; i >= 0; i--)
     {
         LogItem item = logItems[i];
         if (item.item.IsConnected)
         {
             if (item.level >= e.LogLevel)
             {
                 EasyOp.Do(() =>
                 {
                     WriteLine(item.item, $"{e.Time}:{e.Msg}");
                 }, ex =>
                 {
                     //管道写入发生异常,则不再向此管道实例写入日志
                     logItems.RemoveAt(i);
                 });
             }
         }
         else
         {
             logItems.RemoveAt(i);
         }
     }
 }
示例#10
0
        private static void TransferTcp_Ip(IAsyncResult ar)
        {
            RelationTcp_Ip relation = (RelationTcp_Ip)ar.AsyncState;

            if (relation.readTcp.Connected)
            {
                int length = 0;
                EasyOp.Do(() =>
                {
                    length = relation.readTcp.GetStream().EndRead(ar);
                }, () =>
                {
                    EasyOp.Do(() =>
                    {
                        LogUtils.Trace($"接收到数据 From:{relation.readTcp.RemoteEndPoint} length:{length}");
                    });
                    if (length > 0)
                    {
                        if (relation.writeTcp.Connected)
                        {
                            EasyOp.Do(() =>
                            {
                                relation.writeTcp.GetStream().Write(relation.buffer.Take(length).ToArray(), 0, length);
                            }, () =>
                            {
                                EasyOp.Do(() =>
                                {
                                    StartTransferTcp_Ip(relation);
                                }, ex =>
                                {
                                    LogUtils.Debug($"Tcp连接已被断开,读取next数据包失败 {relation.readTcp.RemoteEndPoint}");
                                    relation.writeTcp?.SafeClose();
                                });
                            }, ex =>
                            {
                                LogUtils.Debug($"Tcp连接已被断开,发送数据包失败 {relation.writeTcp.RemoteEndPoint}");
                                relation.readTcp?.SafeClose();
                            });
                        }
                    }
                    else
                    {
                        LogUtils.Debug($"Tcp连接已被断开,接收tcp断开信号 {relation.readTcp.RemoteEndPoint}");
                        relation.writeTcp?.SafeClose();
                    }
                }, ex =>
                {
                    LogUtils.Debug($"数据包读取发生异常 {relation.readTcp.RemoteEndPoint} {ex}");
                    relation.writeTcp?.SafeClose();
                });
            }
            else
            {
                LogUtils.Debug($"Tcp连接已被断开 {relation.readTcp.RemoteEndPoint}");
                relation.writeTcp?.SafeClose();
            }
            //TcpCenter.Instance.ConnectedTcpList.Remove(relation.readTcp);
            //TcpCenter.Instance.ConnectedTcpList.Remove(relation.writeTcp);
        }
示例#11
0
        public override bool Excute()
        {
            LogUtils.Trace($"开始处理消息:0x0201");
            int step = BinaryUtils.ReadInt(m_data);

            //是否第一步创建
            if (step == 1)
            {
                //token,servername,port
                string token      = BinaryUtils.ReadString(m_data);
                string clientName = BinaryUtils.ReadString(m_data);
                int    clientPort = BinaryUtils.ReadInt(m_data);
                int    p2pType    = BinaryUtils.ReadInt(m_data);
                if (p2pTypeDict.ContainsKey(token))
                {
                    p2pTypeDict[token] = p2pType;
                }
                else
                {
                    p2pTypeDict.Add(token, p2pType);
                }
                P2PStart_ServerTransfer(token, clientName, clientPort, p2pType);
            }
            else if (step == 3)
            {
                string clientName = BinaryUtils.ReadString(m_data);
                m_tcpClient.ClientName = clientName;
                string token = BinaryUtils.ReadString(m_data);
                if (clientCenter.WaiteConnetctTcp.ContainsKey(token))
                {
                    if (p2pTypeDict.ContainsKey(token) && p2pTypeDict[token] >= 1)
                    {
                        P2PBind_DirectConnect(token);
                    }
                    else
                    {
                        P2PBind_ServerTransfer(token);
                    }
                    p2pTypeDict.Remove(token);
                }
                else
                {
                    clientCenter.WaiteConnetctTcp.Add(token, m_tcpClient);
                    LogUtils.Debug($"正在等待隧道连接绑定 token:{token}.");
                    EasyInject.Get <AppCenter>().StartNewTask(() =>
                    {
                        Thread.Sleep(appCenter.Config.P2PWaitConnectTime);
                        if (clientCenter.WaiteConnetctTcp.ContainsKey(token))
                        {
                            LogUtils.Debug($"等待隧道连接绑定已超时  token:{token}.");
                            EasyOp.Do(() => m_tcpClient.SafeClose());
                            clientCenter.WaiteConnetctTcp.Remove(token);
                            p2pTypeDict.Remove(token);
                        }
                    });
                }
            }
            return(true);
        }
示例#12
0
 protected virtual void SendError(string token, string msg)
 {
     EasyOp.Do(() =>
     {
         Models.Send.Send_0x0211 sendPacket = new Models.Send.Send_0x0211(token, false, msg);
         m_tcpClient.BeginSend(sendPacket.PackData());
     });
 }
示例#13
0
        public override bool Excute()
        {
            bool ret = true;

            LogUtils.Trace($"开始处理消息:0x0211");
            string token     = BinaryUtils.ReadString(m_data);
            bool   isSuccess = true;
            string msg       = "";

            if (m_data.PeekChar() >= 0)
            {
                isSuccess = BinaryUtils.ReadBool(m_data);
                msg       = BinaryUtils.ReadString(m_data);
            }
            if (isSuccess)
            {
                if (clientCenter.WaiteConnetctTcp.ContainsKey(token))
                {
                    P2PTcpClient client = clientCenter.WaiteConnetctTcp[token];
                    clientCenter.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
                    EasyOp.Do(() => Global_Func.ListenTcp <Packet_0x0212>(client), ex =>
                    {
                        LogUtils.Debug($"命令:0x0211 绑定内网穿透(2端)通道失败,目标Tcp连接已断开");
                        ret = false;
                    });
                }
                else
                {
                    LogUtils.Debug($"命令:0x0211 绑定内网穿透(2端)通道失败,绑定超时");
                    ret = false;
                }
            }
            else
            {
                //失败消息是客户端与服务端的通讯tcp发送的,不能关闭tcp连接
                LogUtils.Debug($"命令:0x0211 From 客户端:{msg}  token:{token}");
                if (clientCenter.WaiteConnetctTcp.ContainsKey(token))
                {
                    //关闭源tcp
                    P2PTcpClient client = clientCenter.WaiteConnetctTcp[token];
                    EasyOp.Do(() => {
                        client?.SafeClose();
                    });
                    clientCenter.WaiteConnetctTcp.Remove(token);
                }
                ret = true;
            }

            return(ret);
        }
示例#14
0
        public void AcceptSocket_Client(IAsyncResult ar)
        {
            ListenSt    st       = (ListenSt)ar.AsyncState;
            TcpListener listener = st.listener;
            Socket      socket   = null;

            EasyOp.Do(() =>
            {
                socket = listener.EndAcceptSocket(ar);
            }, () =>
            {
                EasyOp.Do(() =>
                {
                    listener.BeginAcceptSocket(AcceptSocket_Client, st);
                }, exx =>
                {
                    LogUtils.Error($"端口监听失败:{Environment.NewLine}{exx}");
                    EasyOp.Do(() => listener.Stop());
                    ListenerList.Remove(listener);
                });
                P2PTcpClient tcpClient = null;
                EasyOp.Do(() =>
                {
                    tcpClient = new P2PTcpClient(socket);
                }, () =>
                {
                    LogUtils.Trace($"端口{ appCenter.Config.LocalPort}新连入Tcp:{tcpClient.Client.RemoteEndPoint}");
                    //接收数据
                    EasyOp.Do(() =>
                    {
                        Global_Func.ListenTcp <ReceivePacket>(tcpClient);
                    }, ex =>
                    {
                        LogUtils.Debug($"准备接收Tcp数据出错:{Environment.NewLine}{ex}");
                        EasyOp.Do(() => tcpClient?.SafeClose());
                    });
                }, ex =>
                {
                    LogUtils.Debug($"处理新接入Tcp时出错:{Environment.NewLine}{ex}");
                    EasyOp.Do(() => tcpClient?.SafeClose());
                });
            }, ex =>
            {
                LogUtils.Debug($"获取新接入的Tcp连接失败");
                EasyOp.Do(() =>
                {
                    listener.BeginAcceptSocket(AcceptSocket_Client, st);
                }, exx =>
                {
                    LogUtils.Error($"端口监听失败:{Environment.NewLine}{exx}");
                    EasyOp.Do(() => listener.Stop());
                    ListenerList.Remove(listener);
                });
            });
        }
 public void P2PBind_ServerTransfer(string token)
 {
     P2PTcpClient client = clientCenter.WaiteConnetctTcp[token];
     clientCenter.WaiteConnetctTcp.Remove(token);
     client.IsAuth = m_tcpClient.IsAuth = true;
     client.ToClient = m_tcpClient;
     m_tcpClient.ToClient = client;
     Send_0x0201_Success sendPacket = new Send_0x0201_Success(4);
     EasyOp.Do(() => client.BeginSend(sendPacket.PackData()));
     EasyOp.Do(() => m_tcpClient.BeginSend(sendPacket.PackData()));
     LogUtils.Debug($"成功建立中转模式隧道 token:{token}");
 }
示例#16
0
 /// <summary>
 ///     监听连接外部程序的端口
 /// </summary>
 public void ListenPort()
 {
     EasyOp.Do(() =>
     {
         //  监听端口
         Global_Func.ListenTcp <Packet_0x0202>(m_tcpClient.ToClient);
     }, ex =>
     {
         Utils.LogUtils.Debug($"命令:0x0201  隧道连接失败,源Tcp连接已断开:{Environment.NewLine}{ex}");
         EasyOp.Do(m_tcpClient.SafeClose);
     });
 }
示例#17
0
        public override bool Excute()
        {
            LogUtils.Trace($"开始处理消息:0x0202");
            Send_0x0202 sendPacket = new Send_0x0202(m_data);
            bool        ret        = true;

            EasyOp.Do(() => {
                m_tcpClient.ToClient.BeginSend(sendPacket.PackData());
            }, ex => {
                ret = false;
            });
            return(ret);
        }
        public override bool Excute()
        {
            LogUtils.Trace($"开始处理消息:0x0101");
            bool   ret        = true;
            string clientName = BinaryUtils.ReadString(m_data);
            string authCode   = BinaryUtils.ReadString(m_data);

            if (appCenter.Config.ClientAuthList.Count == 0 || appCenter.Config.ClientAuthList.Any(t => t.Match(clientName, authCode)))
            {
                bool       isSuccess = true;
                P2PTcpItem item      = new P2PTcpItem();
                item.TcpClient = m_tcpClient;
                if (clientCenter.TcpMap.ContainsKey(clientName))
                {
                    if (clientCenter.TcpMap[clientName].TcpClient.IsDisConnected)
                    {
                        clientCenter.TcpMap[clientName].TcpClient?.SafeClose();
                        clientCenter.TcpMap[clientName] = item;
                    }
                    else
                    {
                        isSuccess = false;
                        Send_0x0101 sendPacket = new Send_0x0101(m_tcpClient, false, $"ClientName:{clientName} 已被使用", clientName);
                        LogUtils.Info($"客户端【{clientName}】接入被拒绝,名称被使用,ip:{m_tcpClient.RemoteEndPoint}");
                        EasyOp.Do(() => m_tcpClient.BeginSend(sendPacket.PackData()));
                        ret = false;
                    }
                }
                else
                {
                    clientCenter.TcpMap.Add(clientName, item);
                }
                if (isSuccess)
                {
                    m_tcpClient.IsAuth     = true;
                    m_tcpClient.ClientName = clientName;
                    Send_0x0101 sendPacket = new Send_0x0101(m_tcpClient, true, $"客户端{clientName}认证通过", clientName);
                    m_tcpClient.BeginSend(sendPacket.PackData());
                    LogUtils.Info($"客户端【{clientName}】成功接入,ip:{m_tcpClient.RemoteEndPoint}");
                }
            }
            else
            {
                Send_0x0101 sendPacket = new Send_0x0101(m_tcpClient, false, $"客户端{clientName}认证失败", clientName);
                LogUtils.Info($"客户端【{clientName}】接入被拒绝,授权码错误或客户端名称不在AllowClient内,ip:{m_tcpClient.RemoteEndPoint}");
                m_tcpClient.BeginSend(sendPacket.PackData());
                ret = false;
            }

            return(ret);
        }
示例#19
0
 /// <summary>
 ///     从发起端创建与服务器的tcp连接
 /// </summary>
 /// <param name="token"></param>
 public void CreateTcpFromSource(string token)
 {
     Utils.LogUtils.Debug($"命令:0x0201  正尝试建立中转模式隧道token:{token}");
     if (tcpCenter.WaiteConnetctTcp.ContainsKey(token))
     {
         P2PTcpClient portClient = tcpCenter.WaiteConnetctTcp[token];
         tcpCenter.WaiteConnetctTcp.Remove(token);
         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 =>
                 {
                     Utils.LogUtils.Debug($"命令:0x0201  中转模式隧道,隧道建立失败 token:{token}:{Environment.NewLine} {ex}");
                     EasyOp.Do(serverClient.SafeClose);
                     EasyOp.Do(portClient.SafeClose);
                 });
             }, ex =>
             {
                 Utils.LogUtils.Debug($"命令:0x0201  中转模式隧道,隧道建立失败 token:{token}:{Environment.NewLine} 隧道被服务器强制断开");
                 EasyOp.Do(portClient.SafeClose);
             });
         }, ex =>
         {
             Utils.LogUtils.Debug($"命令:0x0201  中转模式隧道,无法连接服务器 token:{token}:{Environment.NewLine}{ex}");
             EasyOp.Do(portClient.SafeClose);
         });
     }
     else
     {
         LogUtils.Debug($"命令:0x0201 接收到建立中转模式隧道命令,但已超时. token:{token}");
     }
 }
        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());
        }
示例#21
0
 public void CreateTcpFromSource_DirectConnect(string token)
 {
     Models.Send.Send_0x0201_Bind sendPacket = new Models.Send.Send_0x0201_Bind(token);
     Utils.LogUtils.Debug($"命令:0x0201  正尝试建立P2P模式隧道 token:{token}");
     if (tcpCenter.WaiteConnetctTcp.ContainsKey(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.UpdateEndPoint();
             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}");
                     tcpCenter.WaiteConnetctTcp.Remove(token);
                     EasyOp.Do(serverClient.SafeClose);
                 });
             }, ex =>
             {
                 LogUtils.Debug($"命令:0x0201 P2P模式隧道,隧道打洞失败 token:{token}:{Environment.NewLine} 隧道被服务器强制断开");
                 tcpCenter.WaiteConnetctTcp.Remove(token);
             });
         }, ex =>
         {
             LogUtils.Debug($"命令:0x0201 P2P模式隧道,无法连接服务器 token:{token}:{Environment.NewLine}{ex}");
             tcpCenter.WaiteConnetctTcp.Remove(token);
         });
     }
     else
     {
         LogUtils.Debug($"命令:0x0201 接收到建立P2P模式隧道命令,但已超时. token:{token}");
     }
 }
示例#22
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);
        }
示例#24
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}");
            });
        }
示例#25
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}");
     }
 }
示例#26
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>
        ///     直接转发类型的端口监听
        /// </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);
            },
示例#28
0
        public virtual void DoSuccess()
        {
            //  身份验证成功
            string msg = BinaryUtils.ReadString(m_data);

            LogUtils.Info($"命令:0x0101 {msg}");
            tcpCenter.P2PServerTcp.Token = BinaryUtils.ReadString(m_data);
            if (m_data.PeekChar() >= 0)
            {
                string clientName = BinaryUtils.ReadString(m_data);
                appCenter.ClientName = clientName;
                LogUtils.Info($"客户端名称:{appCenter.ClientName}");
            }
            //  发送客户端信息
            Send_0x0103 sendPacket = new Send_0x0103();

            Utils.LogUtils.Info("命令:0x0101 同步服务端数据");
            EasyOp.Do(() => {
                m_tcpClient.Client.Send(sendPacket.PackData());
            });
        }
示例#29
0
 /// <summary>
 ///     监听连接外部程序的端口
 /// </summary>
 protected virtual void ListenPort()
 {
     if (data.PeekChar() >= 0)
     {
         string token = BinaryUtils.ReadString(data);
         if (tcpCenter.WaiteConnetctTcp.ContainsKey(token))
         {
             EasyOp.Do(() =>
             {
                 tcpCenter.WaiteConnetctTcp[token].PulseBlock();
             }, ex =>
             {
                 tcpCenter.WaiteConnetctTcp[token].ErrorMsg = $"命令:0x0201  隧道连接失败,源Tcp连接已断开:{Environment.NewLine}{ex}";
                 tcpCenter.WaiteConnetctTcp[token].PulseBlock();
             });
         }
     }
     else
     {
         Utils.LogUtils.Debug($"命令:0x0201  隧道连接失败,服务端版本过低");
     }
 }
示例#30
0
        public void P2PStart_ServerTransfer(string token, string clientName, int clientPort, int p2pType)
        {
            P2PTcpItem item = null;

            if (clientCenter.TcpMap.ContainsKey(clientName))
            {
                item = clientCenter.TcpMap[clientName];
            }
            if (item != null && item.TcpClient.Connected)
            {
                if (item.BlackClients.Contains(m_tcpClient.ClientName))
                {
                    Send_0x0201_Failure sendPacket = new Send_0x0201_Failure($"客户端{clientName}已被加入黑名单");
                    LogUtils.Warning($"建立隧道失败,客户端{clientName}已被加入黑名单");
                    EasyOp.Do(() => m_tcpClient.BeginSend(sendPacket.PackData()));
                }
                else if (item.AllowPorts.Any(t => t.Match(clientPort, m_tcpClient.ClientName)))
                {
                    LogUtils.Debug($"通知客户端开始建立{(p2pType >= 1 ? "打洞" : "中转")}模式隧道 token{token}");
                    Send_0x0201_Success sendDPacket = new Send_0x0201_Success(token, clientPort, p2pType);
                    Send_0x0201_Success sendSPacket = new Send_0x0201_Success(token, p2pType);
                    clientCenter.TcpMap[clientName].TcpClient.BeginSend(sendDPacket.PackData());
                    EasyOp.Do(() => m_tcpClient.BeginSend(sendSPacket.PackData()));
                }
                else
                {
                    Send_0x0201_Failure sendPacket = new Send_0x0201_Failure($"未获得授权,无法建立隧道,端口{clientPort}");
                    LogUtils.Debug($"未获得授权,无法建立隧道,端口{clientPort}");
                    EasyOp.Do(() => m_tcpClient.BeginSend(sendPacket.PackData()));
                }
            }
            else
            {
                //发送客户端未在线
                LogUtils.Debug($"【P2P】客户端{clientName}不在线.");
                Send_0x0201_Failure sendPacket = new Send_0x0201_Failure($"客户端{clientName}不在线");
                EasyOp.Do(() => m_tcpClient.BeginSend(sendPacket.PackData()));
            }
        }