Ejemplo n.º 1
0
 /// <summary>
 /// Updates the session.
 /// </summary>
 /// <param name="TSession">The T session.</param>
 private void UpdateSession(eTerm363Session TSession)
 {
     try {
         TSessionSetup Seup    = ASyncSetup.SessionCollection.SingleOrDefault <TSessionSetup>(Fun => Fun.SessionPass == TSession.userPass && Fun.SessionCode == TSession.userName);
         SocketTraffic Traffic = Seup.Traffics[Seup.Traffics.IndexOf(new SocketTraffic(DateTime.Now.ToString(@"yyyyMM")))];
         Traffic.Traffic++;
         Traffic.UpdateDate = DateTime.Now;
     }
     catch { }
 }
Ejemplo n.º 2
0
        /// <summary>
        /// 开始服务.
        /// </summary>
        public void BeginAsync()
        {
            if (!LicenceManager.Instance.ValidateResult)
            {
                throw new OverflowException(__eTerm443Packet.AUTHERROR_MES);
            }
            StackNetPoint               = new IPEndPoint(IPAddress.Any, this.__Setup.ExternalPort ?? 360);
            __asyncServer               = new eTermAsyncServer(StackNetPoint, SID, RID);
            __asyncServer.MaxSession    = LicenceManager.Instance.LicenceBody.MaxTSession;
            __asyncServer.OnPacketSent += new EventHandler <AsyncEventArgs <eTerm363Packet, eTerm363Packet, eTerm363Session> >(
                delegate(object sender, AsyncEventArgs <eTerm363Packet, eTerm363Packet, eTerm363Session> e)
            {
                if (OnTSessionPacketSent != null)
                {
                    OnTSessionPacketSent(sender, e);
                }
            }
                );

            this.TSessionValidate = new AsyncBaseServer <eTerm363Session, eTerm363Packet> .ValidateCallback(delegate(eTerm363Session s, eTerm363Packet p, out string ValidateMessage, out int ClientType)
            {
                s.UnpakcetSession(p);
                ClientType             = 0;
                string clientMessage   = string.Empty;
                TSessionSetup TSession = ASyncSetup.SessionCollection.SingleOrDefault <TSessionSetup>(Fun =>
                                                                                                      (Fun.ExpireDate != null || Fun.ExpireDate <= DateTime.Now)
                                                                                                      &&
                                                                                                      Fun.SessionPass == s.userPass
                                                                                                      &&
                                                                                                      Fun.SessionCode == s.userName
                                                                                                      &&
                                                                                                      Fun.IsOpen == true
                                                                                                      );
                if (TSession == null)
                {
                    ValidateMessage = string.Format(@"{0} 登录帐号或密码错误", s.userName); return(false);
                }

                s.TSessionInterval    = TSession.SessionExpire;
                s.UnallowableReg      = TSession.ForbidCmdReg;
                s.SpecialIntervalList = TSession.SpecialIntervalList;
                s.userGroup           = TSession.GroupCode;
                ValidateMessage       = string.Format(@"欢迎使用 {0} 共享终端,时限:{1}秒 {2}.", LicenceManager.Instance.LicenceBody.Company, s.TSessionInterval, DateTime.Now.ToString(@"yyyy-MM-dd HH:mm:ss"));
                string currentMonth   = string.Format(@"{0}", DateTime.Now.ToString(@"yyyyMM"));
                if (!TSession.Traffics.Contains(new SocketTraffic(currentMonth)))
                {
                    TSession.Traffics.Add(new SocketTraffic()
                    {
                        MonthString = currentMonth, Traffic = 0.0, UpdateDate = DateTime.Now
                    });
                }
                SocketTraffic Traffic = TSession.Traffics[TSession.Traffics.IndexOf(new SocketTraffic(currentMonth))];
                if (Traffic.Traffic >= TSession.FlowRate)
                {
                    return(false);
                }

                #region eTerm端类型
                ClientType = p.OriginalBytes[0x9F] == 0x00 ? 0 : 1;
                //SDK终端
                if (ClientType == 0 && !(LicenceManager.Instance.LicenceBody.AlloweTermClient ?? false))
                {
                    ValidateMessage = @"服务器授权不允许使用eTerm终端进行连接";
                    return(false);
                }

                #endregion

                #region 关闭其它登录终端
                if (!(TSession.AllowDuplicate ?? false))
                {
                    foreach (var connect in
                             from entry in __asyncServer.TSessionCollection
                             where entry.userName == s.userName && entry.SessionId != s.SessionId
                             orderby entry.LastActive ascending
                             select entry)
                    {
                        clientMessage = string.Format(@"登录退出[{0}],该帐号已在另外的地址登录[{1} {2}]", (connect.AsyncSocket.RemoteEndPoint as IPEndPoint).Address.ToString(), (s.AsyncSocket.RemoteEndPoint as IPEndPoint).Address.ToString(), DateTime.Now.ToString(@"MM dd HH:mm:ss"));
                        connect.SendPacket(__eTerm443Packet.BuildSessionPacket(this.SID, this.RID, clientMessage));
                        connect.ObligatoryReconnect = false;
                        new Timer(new TimerCallback(
                                      delegate(object sender)
                        {
                            connect.Close();
                        }), null, 1000, Timeout.Infinite);
                    }
                }
                #endregion

                if (this.OnTSessionValidated != null)
                {
                    this.OnTSessionValidated(s, new AsyncEventArgs <eTerm363Session>(s));
                }
                return(true);
            });


            __asyncServer.OnReadPacket += new EventHandler <AsyncEventArgs <eTerm363Packet, eTerm363Packet, eTerm363Session> >(
                delegate(object sender, AsyncEventArgs <eTerm363Packet, eTerm363Packet, eTerm363Session> e)
            {
                string Command = Encoding.GetEncoding("gb2312").GetString(e.Session.UnInPakcet(e.InPacket)).Trim().ToLower();
                if (this.OnTSessionReadPacket != null)
                {
                    this.OnTSessionReadPacket(sender, e);
                }
                #region 指令拦截
                if (!string.IsNullOrEmpty(e.Session.UnallowableReg) && Regex.IsMatch(Command, e.Session.UnallowableReg, RegexOptions.IgnoreCase | RegexOptions.Multiline))
                {
                    e.Session.SendPacket(__eTerm443Packet.BuildSessionPacket(e.Session.SID, e.Session.RID, string.Format(@"{0} 指令未授权", Command)));
                    return;
                }
                #endregion

                UpdateSession(e.Session);

                #region 后台处理插件
                if (LicenceManager.Instance.LicenceBody.AllowAfterValidate)
                {
                    try {
                        foreach (var PlugIn in
                                 from entry in AsyncStackNet.Instance.ASyncSetup.PlugInCollection
                                 where Command.ToLower().StartsWith(entry.PlugInName.ToLower())
                                 orderby entry.PlugInName ascending
                                 select entry)
                        {
                            if (PlugIn.ClientSessionInstance == null)
                            {
                                continue;
                            }
                            PlugIn.ClientSessionInstance.BeginExecute(new AsyncCallback(delegate(IAsyncResult iar)
                            {
                                PlugIn.ClientSessionInstance.EndExecute(iar);
                            }), e.Session, e.InPacket, e.OutPacket, LicenceManager.Instance.LicenceBody);
                            return;
                        }
                    }
                    catch (Exception ex) {
                        FireExcetion(new ErrorEventArgs(ex), e.Session);
                        //return;
                    }
                }
                #endregion

                GetActiveAsync(e.Session);
                if (e.Session.Async443 == null)
                {
                    e.Session.SendPacket(__eTerm443Packet.NoAsyncSocketInfo(e.Session.SID, e.Session.RID));
                }
                else
                {
                    byte[] PacketBytes;
                    PacketBytes    = e.InPacket.OriginalBytes;
                    PacketBytes[8] = e.Session.Async443.SID;
                    PacketBytes[9] = e.Session.Async443.RID;
                    e.Session.Async443.SendPacket(PacketBytes);
                }
            }
                );
            __asyncServer.TSessionValidate  = TSessionValidate;
            __asyncServer.OnTSessionAccept += new EventHandler <AsyncEventArgs <eTerm363Session> >(
                delegate(object sender, AsyncEventArgs <eTerm363Session> e)
            {
                if (this.OnTSessionAccept != null)
                {
                    this.OnTSessionAccept(sender, e);
                }

                e.Session.ReleaseIntervalSet = new ReleaseIntervalSetDelegate(delegate(string packet, eTerm363Session TSession)
                {
                    try {
                        if (!string.IsNullOrEmpty(TSession.SpecialIntervalList))
                        {
                            string SpecialPacket = Regex.Replace(TSession.SpecialIntervalList, @"\d+\,", string.Empty, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                            SpecialPacket        = SpecialPacket.Substring(0, SpecialPacket.Length - 1);
                            Match specialMatch   = Regex.Match(packet, SpecialPacket, RegexOptions.Multiline | RegexOptions.IgnoreCase);
                            if (!string.IsNullOrEmpty(packet) && Regex.IsMatch(packet, SpecialPacket, RegexOptions.Multiline | RegexOptions.IgnoreCase))
                            {
                                return(int.Parse(Regex.Match(TSession.SpecialIntervalList, string.Format(@"\^({0})\|(\d+)", specialMatch.Value), RegexOptions.IgnoreCase | RegexOptions.Multiline).Groups[2].Value));
                            }
                            return(TSession.TSessionInterval);
                        }
                    }
                    catch { }
                    finally { }
                    return(TSession.TSessionInterval);
                });

                e.Session.OnTSessionRelease += new EventHandler <AsyncEventArgs <eTerm363Session> >(
                    delegate(object Session, AsyncEventArgs <eTerm363Session> ie)
                {
                    if (OnTSessionRelease != null)
                    {
                        OnTSessionRelease(Session, ie);
                    }
                    ie.Session.SendPacket(__eTerm443Packet.BuildSessionPacket(ie.Session.SID, ie.Session.RID, "注意,配置已释放,指令上下文可能已经丢失."));
                    if (ie.Session.Async443 == null)
                    {
                        return;
                    }
                    ie.Session.Async443.SendPacket("IG");
                    ie.Session.Async443.TSession = null;
                    ie.Session.Async443          = null;
                }
                    );
            }
                );
            __asyncServer.OnTSessionClosed += new EventHandler <AsyncEventArgs <eTerm363Session> >(
                delegate(object sender, AsyncEventArgs <eTerm363Session> e)
            {
                UpdateSession(e.Session);
                if (this.OnTSessionClosed != null)
                {
                    this.OnTSessionClosed(sender, e);
                }
                if (e.Session.Async443 == null)
                {
                    return;
                }
                e.Session.Async443.TSession = null;
            }
                );
            __asyncServer.Start();

            __rateAsync = new Timer(
                new TimerCallback(
                    delegate(object sender)
            {
                if (OnRateEvent != null)
                {
                    OnRateEvent(sender, EventArgs.Empty);
                }
            }),
                null, (this.ASyncSetup.StatisticalFrequency ?? 10) * 1000 * 60, (this.ASyncSetup.StatisticalFrequency ?? 10) * 1000 * 60);

            ConnectCore();

            AppendAsync();
        }