public Task StartAsync(CancellationToken cancellationToken)
        {
            TServerTransport serverTransport = new TServerSocketTransport(Configuration.GetValue <int>("RpcPort"));

            TBinaryProtocol.Factory factory1 = new TBinaryProtocol.Factory();
            TBinaryProtocol.Factory factory2 = new TBinaryProtocol.Factory();

            TBaseServer server = new AsyncBaseServer(Processor, serverTransport, factory1, factory2, LoggerFactory);

            return(server.ServeAsync(cancellationToken));
        }
Example #2
0
        public static void Run(CancellationToken cancellationToken, LoggerFactory loggerFactory)
        {
            TServerTransport serverTransport = new TServerSocketTransport(8005);

            ITProtocolFactory inputProtocolFactory  = new TCompactProtocol.Factory();
            ITProtocolFactory outputProtocolFactory = new TCompactProtocol.Factory();

            var processor = new IHelloWorldService.AsyncProcessor(new HelloWorldService());

            var server = new AsyncBaseServer(processor, serverTransport, inputProtocolFactory, outputProtocolFactory, loggerFactory);

            server.ServeAsync(cancellationToken);
        }
Example #3
0
        public static async Task RunAsync(IAsync processor, int port, ILoggerFactory loggerFactory)
        {
            using (var source = new CancellationTokenSource())
            {
                var server = new AsyncBaseServer(
                    new AsyncProcessor(processor),
                    new TServerSocketTransport(port),
                    new TBinaryProtocol.Factory(),
                    new TBinaryProtocol.Factory(),
                    loggerFactory
                    );

                await server.ServeAsync(source.Token);
            }
        }
Example #4
0
        static async Task RunNotificationServiceAsync()
        {
            var fabric  = new LoggerFactory().AddConsole(LogLevel.Trace);
            var handler = new NotificationHandler();

            ITAsyncProcessor processor       = null;
            TServerTransport serverTransport = null;

            serverTransport = new TServerSocketTransport(9090);

            ITProtocolFactory inputProtocolFactory;
            ITProtocolFactory outputProtocolFactory;

            inputProtocolFactory  = new TBinaryProtocol.Factory();
            outputProtocolFactory = new TBinaryProtocol.Factory();
            processor             = new NotificationService.AsyncProcessor(handler);

            var server = new AsyncBaseServer(processor, serverTransport, inputProtocolFactory, outputProtocolFactory, fabric);
            await server.ServeAsync(new CancellationToken());
        }
Example #5
0
        private static async Task RunSelectedConfigurationAsync(Transport transport, Protocol protocol, CancellationToken cancellationToken)
        {
            var fabric  = new LoggerFactory().AddConsole(LogLevel.Trace).AddDebug(LogLevel.Trace);
            var handler = new ThriftService();
            ITAsyncProcessor processor       = null;
            TServerTransport serverTransport = null;

            switch (transport)
            {
            case Transport.Tcp:
                serverTransport = new TServerSocketTransport(9090);
                break;

            case Transport.TcpBuffered:
                serverTransport = new TServerSocketTransport(9090, 10000, true);
                break;

            case Transport.NamedPipe:
                serverTransport = new TNamedPipeServerTransport(".test");
                break;

            case Transport.TcpTls:
                serverTransport = new TTlsServerSocketTransport(9090, false, GetCertificate(), ClientCertValidator, LocalCertificateSelectionCallback);
                break;

            case Transport.Framed:
                serverTransport = new TServerFramedTransport(9090);
                break;
            }

            ITProtocolFactory inputProtocolFactory;
            ITProtocolFactory outputProtocolFactory;

            switch (protocol)
            {
            case Protocol.Binary:
                inputProtocolFactory  = new TBinaryProtocol.Factory();
                outputProtocolFactory = new TBinaryProtocol.Factory();
                processor             = new Calculator.AsyncProcessor(handler);
                break;

            case Protocol.Compact:
                inputProtocolFactory  = new TCompactProtocol.Factory();
                outputProtocolFactory = new TCompactProtocol.Factory();
                processor             = new Calculator.AsyncProcessor(handler);
                break;

            case Protocol.Json:
                inputProtocolFactory  = new TJsonProtocol.Factory();
                outputProtocolFactory = new TJsonProtocol.Factory();
                processor             = new Calculator.AsyncProcessor(handler);
                break;

            case Protocol.Multiplexed:
                inputProtocolFactory  = new TBinaryProtocol.Factory();
                outputProtocolFactory = new TBinaryProtocol.Factory();

                var calcHandler   = new ThriftService();
                var calcProcessor = new Calculator.AsyncProcessor(calcHandler);

                var calcHandlerShared   = new SharedServiceAsyncHandler();
                var calcProcessorShared = new SharedService.AsyncProcessor(calcHandlerShared);


                var multiplexedProcessor = new TMultiplexedProcessor();
                multiplexedProcessor.RegisterProcessor(nameof(Calculator), calcProcessor);
                multiplexedProcessor.RegisterProcessor(nameof(SharedService), calcProcessorShared);

                processor = multiplexedProcessor;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(protocol), protocol, null);
            }

            try
            {
                Logger.LogInformation(
                    $"Selected TAsyncServer with {serverTransport} transport, {processor} processor and {inputProtocolFactory} protocol factories");

                var server = new AsyncBaseServer(processor, serverTransport, inputProtocolFactory, outputProtocolFactory, fabric);

                Logger.LogInformation("Starting the server ...");

                await server.ServeAsync(cancellationToken);
            }
            catch (Exception ex)
            {
                Logger.LogInformation(ex, ex.Message);
            }
        }
Example #6
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();
        }
Example #7
0
        private static async Task RunSelectedConfigurationAsync(Transport transport,
                                                                Protocol protocol, CancellationToken cancellationToken)
        {
            var fabric    = new LoggerFactory();
            var handler   = new CalculatorAsyncHandler();
            var processor = new Calculator.AsyncProcessor(handler);

            TServerTransport serverTransport = null;

            switch (transport)
            {
            case Transport.Tcp:
                serverTransport = new TServerSocketTransport(9090);
                break;

            case Transport.TcpBuffered:
                serverTransport = new TServerSocketTransport(port: 9090, clientTimeout: 10000,
                                                             useBufferedSockets: true);
                break;

            case Transport.NamedPipe:
                serverTransport = new TNamedPipeServerTransport(".test");
                break;

            case Transport.TcpTls:
                serverTransport = new TTlsServerSocketTransport(9090, false, GetCertificate(),
                                                                ClientCertValidator, LocalCertificateSelectionCallback);
                break;
            }

            ITProtocolFactory inputProtocolFactory;
            ITProtocolFactory outputProtocolFactory;

            switch (protocol)
            {
            case Protocol.Binary:
            {
                inputProtocolFactory  = new TBinaryProtocol.Factory();
                outputProtocolFactory = new TBinaryProtocol.Factory();
            }
            break;

            case Protocol.Compact:
            {
                inputProtocolFactory  = new TCompactProtocol.Factory();
                outputProtocolFactory = new TCompactProtocol.Factory();
            }
            break;

            case Protocol.Json:
            {
                inputProtocolFactory  = new TJsonProtocol.Factory();
                outputProtocolFactory = new TJsonProtocol.Factory();
            }
            break;

            default:
                throw new ArgumentOutOfRangeException(nameof(protocol), protocol, null);
            }

            try
            {
                Logger.LogInformation(
                    $"Selected TAsyncServer with {serverTransport} transport and {inputProtocolFactory} protocol factories");

                var server = new AsyncBaseServer(processor, serverTransport, inputProtocolFactory,
                                                 outputProtocolFactory, fabric);

                Logger.LogInformation("Starting the server...");
                await server.ServeAsync(cancellationToken);
            }
            catch (Exception x)
            {
                Logger.LogInformation(x.ToString());
            }

            Logger.LogInformation("Server stopped.");
        }
        public static int Execute(List <string> args)
        {
            var logger = new LoggerFactory().CreateLogger("Test");

            try
            {
                var param = new ServerParam();

                try
                {
                    param.Parse(args);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("*** FAILED ***");
                    Console.WriteLine("Error while  parsing arguments");
                    Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
                    return(1);
                }


                // Transport
                TServerTransport trans;
                if (param.pipe != null)
                {
                    trans = new TNamedPipeServerTransport(param.pipe);
                }
                else
                {
                    if (param.useEncryption)
                    {
                        var certPath = "../../keys/server.p12";
                        trans = new TTlsServerSocketTransport(param.port, param.useBufferedSockets, new X509Certificate2(certPath, "thrift"), null, null, SslProtocols.Tls);
                    }
                    else
                    {
                        trans = new TServerSocketTransport(param.port, 0, param.useBufferedSockets);
                    }
                }

                ITProtocolFactory proto;
                if (param.compact)
                {
                    proto = new TCompactProtocol.Factory();
                }
                else if (param.json)
                {
                    proto = new TJsonProtocol.Factory();
                }
                else
                {
                    proto = new TBinaryProtocol.Factory();
                }

                ITProcessorFactory processorFactory;

                // Processor
                var testHandler   = new TestHandlerAsync();
                var testProcessor = new ThriftAsync.Test.ThriftTest.AsyncProcessor(testHandler);
                processorFactory = new SingletonTProcessorFactory(testProcessor);


                TTransportFactory transFactory;
                if (param.useFramed)
                {
                    throw new NotImplementedException("framed"); // transFactory = new TFramedTransport.Factory();
                }
                else
                {
                    transFactory = new TTransportFactory();
                }

                TBaseServer serverEngine = new AsyncBaseServer(processorFactory, trans, transFactory, transFactory, proto, proto, logger);

                //Server event handler
                var serverEvents = new MyServerEventHandler();
                serverEngine.SetEventHandler(serverEvents);

                // Run it
                var where = (!string.IsNullOrEmpty(param.pipe)) ? "on pipe " + param.pipe : "on port " + param.port;
                Console.WriteLine("Starting the AsyncBaseServer " + where +
                                  " with processor TPrototypeProcessorFactory prototype factory " +
                                  (param.useBufferedSockets ? " with buffered socket" : "") +
                                  (param.useFramed ? " with framed transport" : "") +
                                  (param.useEncryption ? " with encryption" : "") +
                                  (param.compact ? " with compact protocol" : "") +
                                  (param.json ? " with json protocol" : "") +
                                  "...");
                serverEngine.ServeAsync(CancellationToken.None).GetAwaiter().GetResult();
                Console.ReadLine();
            }
            catch (Exception x)
            {
                Console.Error.Write(x);
                return(1);
            }
            Console.WriteLine("done.");
            return(0);
        }
Example #9
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();
        }
Example #10
0
        public static int Execute(List <string> args)
        {
            var loggerFactory = new LoggerFactory();//.AddConsole().AddDebug();
            var logger        = new LoggerFactory().CreateLogger("Test");

            try
            {
                var param = new ServerParam();

                try
                {
                    param.Parse(args);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("*** FAILED ***");
                    Console.WriteLine("Error while  parsing arguments");
                    Console.WriteLine(ex.Message + " ST: " + ex.StackTrace);
                    return(1);
                }


                // Transport
                TServerTransport trans;
                if (param.pipe != null)
                {
                    trans = new TNamedPipeServerTransport(param.pipe);
                }
//                else if (param.useFramed)
//                {
//                    trans = new TServerFramedTransport(param.port);
//                }
                else
                {
                    if (param.useEncryption)
                    {
                        var cert = GetServerCert();

                        if (cert == null || !cert.HasPrivateKey)
                        {
                            throw new InvalidOperationException("Certificate doesn't contain private key");
                        }

                        trans = new TTlsServerSocketTransport(param.port, param.useBufferedSockets, param.useFramed, cert,
                                                              (sender, certificate, chain, errors) => true,
                                                              null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12);
                    }
                    else
                    {
                        trans = new TServerSocketTransport(param.port, 0, param.useBufferedSockets, param.useFramed);
                    }
                }

                ITProtocolFactory proto;
                if (param.compact)
                {
                    proto = new TCompactProtocol.Factory();
                }
                else if (param.json)
                {
                    proto = new TJsonProtocol.Factory();
                }
                else
                {
                    proto = new TBinaryProtocol.Factory();
                }

                ITProcessorFactory processorFactory;

                // Processor
                var testHandler   = new TestHandlerAsync();
                var testProcessor = new ThriftTest.AsyncProcessor(testHandler);
                processorFactory = new SingletonTProcessorFactory(testProcessor);

                TTransportFactory transFactory = new TTransportFactory();

                TBaseServer serverEngine = new AsyncBaseServer(processorFactory, trans, transFactory, transFactory, proto, proto, logger);

                //Server event handler
                var serverEvents = new MyServerEventHandler();
                serverEngine.SetEventHandler(serverEvents);

                // Run it
                var where = (!string.IsNullOrEmpty(param.pipe)) ? "on pipe " + param.pipe : "on port " + param.port;
                Console.WriteLine("Starting the AsyncBaseServer " + where +
                                  " with processor TPrototypeProcessorFactory prototype factory " +
                                  (param.useBufferedSockets ? " with buffered socket" : "") +
                                  (param.useFramed ? " with framed transport" : "") +
                                  (param.useEncryption ? " with encryption" : "") +
                                  (param.compact ? " with compact protocol" : "") +
                                  (param.json ? " with json protocol" : "") +
                                  "...");
                serverEngine.ServeAsync(CancellationToken.None).GetAwaiter().GetResult();
                Console.ReadLine();
            }
            catch (Exception x)
            {
                Console.Error.Write(x);
                return(1);
            }
            Console.WriteLine("done.");
            return(0);
        }