/// <summary>
 ///     监听消息端口
 /// </summary>
 private void ListenMessagePort()
 {
     try
     {
         TcpListener listener = new TcpListener(IPAddress.Any, Global.LocalPort);
         listener.Start();
         ListenerList.Add(listener);
         Global.TaskFactory.StartNew(() =>
         {
             try
             {
                 while (true)
                 {
                     Socket socket          = listener.AcceptSocket();
                     P2PTcpClient tcpClient = new P2PTcpClient(socket);
                     //接收数据
                     Global.TaskFactory.StartNew(() =>
                     {
                         Global_Func.ListenTcp <ReceivePacket>(tcpClient);
                     });
                 }
             }
             catch (Exception ex)
             {
                 LogUtils.Debug(ex.Message);
             }
         });
     }
     catch
     {
         LogUtils.Error($"【失败】服务端口:{Global.LocalPort} 监听失败.");
     }
 }
Example #2
0
        /// <summary>
        ///     监听消息端口
        /// </summary>
        private void ListenMessagePort()
        {
            TcpListener listener = new TcpListener(IPAddress.Any, ConfigCenter.Instance.LocalPort);

            try
            {
                listener.Start();
                LogUtils.Info($"【成功】启动服务,端口:{ConfigCenter.Instance.LocalPort}");
            }
            catch
            {
                LogUtils.Error($"【失败】服务端口:{ConfigCenter.Instance.LocalPort} 监听失败.");
                return;
            }
            ListenerList.Add(listener);
            AppCenter.Instance.StartNewTask(() =>
            {
                try
                {
                    while (true)
                    {
                        Socket socket          = listener.AcceptSocket();
                        P2PTcpClient tcpClient = new P2PTcpClient(socket);
                        LogUtils.Info($"端口{ ConfigCenter.Instance.LocalPort}新连入Tcp:{tcpClient.Client.RemoteEndPoint.ToString()}");
                        //接收数据
                        AppCenter.Instance.StartNewTask(() => Global_Func.ListenTcp <ReceivePacket>(tcpClient));
                    }
                }
                catch (Exception ex)
                {
                    LogUtils.Debug(ex.Message);
                }
            });
        }
Example #3
0
        public static void ListenTcp <T>(P2PTcpClient tcpClient) where T : ReceivePacket
        {
            try
            {
                Guid          curGuid    = Global.CurrentGuid;
                byte[]        buffer     = new byte[P2PGlobal.P2PSocketBufferSize];
                NetworkStream tcpStream  = tcpClient.GetStream();
                ReceivePacket msgReceive = Activator.CreateInstance(typeof(T)) as ReceivePacket;
                while (tcpClient.Connected && curGuid == Global.CurrentGuid)
                {
                    int curReadLength = tcpStream.ReadSafe(buffer, 0, buffer.Length);
                    if (curReadLength > 0)
                    {
                        byte[] refData = buffer.Take(curReadLength).ToArray();
                        while (msgReceive.ParseData(ref refData))
                        {
                            LogUtils.Debug($"命令类型:{msgReceive.CommandType}");
                            // 执行command
                            using (P2PCommand command = FindCommand(tcpClient, msgReceive))
                            {
                                command?.Excute();
                            }
                            //重置msgReceive
                            msgReceive.Reset();
                            if (refData.Length <= 0)
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtils.Error($"【错误】Global_Func.ListenTcp:{Environment.NewLine}{ex}");
            }

            if (Global.TcpMap.ContainsKey(tcpClient.ClientName))
            {
                if (Global.TcpMap[tcpClient.ClientName].TcpClient == tcpClient)
                {
                    Global.TcpMap.Remove(tcpClient.ClientName);
                }
            }
            //如果tcp已关闭,需要关闭相关tcp
            try
            {
                tcpClient.ToClient?.Close();
            }
            catch { }
            LogUtils.Debug($"tcp连接{tcpClient.RemoteEndPoint}已断开");
        }
Example #4
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);
                });
            });
        }
Example #5
0
        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}");
                });
            });
        }
Example #6
0
        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}");
                });
            });
        }
        private static void ReadTcp_Server(IAsyncResult ar)
        {
            RelationTcp_Server relation = (RelationTcp_Server)ar.AsyncState;

            if (relation.guid == EasyInject.Get <AppCenter>().CurrentGuid)
            {
                if (relation.readTcp.Connected && relation.readTcp.GetStream().CanRead)
                {
                    int length = 0;
                    EasyOp.Do(() =>
                    {
                        length = relation.readTcp.GetStream().EndRead(ar);
                    }, () =>
                    {
                        if (length > 0)
                        {
                            byte[] refData = relation.buffer.Take(length).ToArray();
                            while (relation.msgReceive.ParseData(ref refData))
                            {
                                // 执行command
                                using (P2PCommand command = FindCommand(relation.readTcp, relation.msgReceive))
                                {
                                    //LogUtils.Trace($"命令类型:{relation.msgReceive.CommandType}");
                                    if (command != null)
                                    {
                                        bool isSuccess = false;
                                        EasyOp.Do(() =>
                                        {
                                            isSuccess = command.Excute();
                                        },
                                                  e =>
                                        {
                                            LogUtils.Error($"执行命令{relation.msgReceive.CommandType}时发生异常:{e}");
                                        });
                                        if (!isSuccess)
                                        {
                                            EasyOp.Do(() => { relation.readTcp?.SafeClose(); });
                                            EasyOp.Do(() => { relation.readTcp.ToClient?.SafeClose(); });
                                            return;
                                        }
                                    }
                                    else
                                    {
                                        EasyOp.Do(() => { relation.readTcp?.SafeClose(); });
                                        EasyOp.Do(() => { relation.readTcp.ToClient?.SafeClose(); });
                                        return;
                                    }
                                }
                                //重置msgReceive
                                relation.msgReceive.Reset();
                                if (refData.Length <= 0)
                                {
                                    break;
                                }
                            }
                            if (relation.readTcp.Connected)
                            {
                                EasyOp.Do(() =>
                                {
                                    relation.readTcp.GetStream().BeginRead(relation.buffer, 0, relation.buffer.Length, ReadTcp_Server, relation);
                                }, ex =>
                                {
                                    LogUtils.Debug($"Tcp连接已被断开 {relation.readTcp.RemoteEndPoint}");
                                    EasyOp.Do(() => { relation.readTcp.ToClient?.SafeClose(); });
                                });
                            }
                        }
                        else
                        {
                            EasyOp.Do(() => { relation.readTcp?.SafeClose(); });
                            EasyOp.Do(() => { relation.readTcp.ToClient?.SafeClose(); });
                        }
                    }, ex =>
                    {
                        LogUtils.Debug($"Tcp连接已被断开 {relation.readTcp.RemoteEndPoint}");
                        EasyOp.Do(() => { relation.readTcp.ToClient?.SafeClose(); });
                    });
                }
            }
            else
            {
                LogUtils.Debug($"主动断开{relation.readTcp.RemoteEndPoint}连接");
                EasyOp.Do(() => { relation.readTcp?.SafeClose(); });
                EasyOp.Do(() => { relation.readTcp.ToClient?.SafeClose(); });
            }
            //if (TcpCenter.Instance.ConnectedTcpList.Contains(relation.readTcp))
            //    TcpCenter.Instance.ConnectedTcpList.Remove(relation.readTcp);
        }
        public static void ListenTcp <T>(P2PTcpClient tcpClient) where T : ReceivePacket
        {
            try
            {
                Guid          curGuid   = AppCenter.Instance.CurrentGuid;
                byte[]        buffer    = new byte[P2PGlobal.P2PSocketBufferSize];
                NetworkStream tcpStream = tcpClient.GetStream();
                tcpClient.ReceiveBufferSize = P2PGlobal.P2PSocketBufferSize;
                ReceivePacket msgReceive = Activator.CreateInstance(typeof(T)) as ReceivePacket;

                int   maxTotal      = 1024 * 50 * 2;
                int[] recieveLength = new int[2];
                int   lastSecond    = -1;


                while (tcpClient.Connected && curGuid == AppCenter.Instance.CurrentGuid)
                {
                    int curReadLength = tcpStream.ReadSafe(buffer, 0, buffer.Length);
                    if (curReadLength > 0)
                    {
                        byte[] refData = buffer.Take(curReadLength).ToArray();
                        if (tcpClient.IsSpeedLimit)
                        {
                            int curSecond = DateTime.Now.Second;
                            if (DateTime.Now.Second != lastSecond)
                            {
                                recieveLength[curSecond % 2] = 0;
                            }
                            lastSecond = curSecond;
                            recieveLength[curSecond % 2] += curReadLength;
                            if (recieveLength.Sum() > maxTotal)
                            {
                                Thread.Sleep(1000);
                            }
                        }


                        while (msgReceive.ParseData(ref refData))
                        {
                            LogUtils.Debug($"命令类型:{msgReceive.CommandType}");
                            // 执行command
                            using (P2PCommand command = FindCommand(tcpClient, msgReceive))
                            {
                                command?.Excute();
                            }
                            //重置msgReceive
                            msgReceive.Reset();
                            if (refData.Length <= 0)
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtils.Error($"【错误】Global_Func.ListenTcp:{Environment.NewLine}{ex}");
            }

            if (ClientCenter.Instance.TcpMap.ContainsKey(tcpClient.ClientName))
            {
                if (ClientCenter.Instance.TcpMap[tcpClient.ClientName].TcpClient == tcpClient)
                {
                    ClientCenter.Instance.TcpMap.Remove(tcpClient.ClientName);
                }
            }
            //如果tcp已关闭,需要关闭相关tcp
            try
            {
                tcpClient.ToClient?.SafeClose();
            }
            catch { }
            LogUtils.Debug($"tcp连接{tcpClient.RemoteEndPoint}已断开");
        }