Пример #1
1
        private static async Task RunSelectedConfigurationAsync(Transport transport, Buffering buffering, Protocol protocol, bool multiplex, CancellationToken cancellationToken)
        {
            TServerTransport serverTransport = transport switch
            {
                Transport.Tcp => new TServerSocketTransport(9090, Configuration),
                Transport.NamedPipe => new TNamedPipeServerTransport(".test", Configuration, NamedPipeClientFlags.None),
                Transport.TcpTls => new TTlsServerSocketTransport(9090, Configuration, GetCertificate(), ClientCertValidator, LocalCertificateSelectionCallback),
                _ => throw new ArgumentException("unsupported value $transport", nameof(transport)),
            };

            TTransportFactory transportFactory = buffering switch
            {
                Buffering.Buffered => new TBufferedTransport.Factory(),
                Buffering.Framed => new TFramedTransport.Factory(),
                // layered transport(s) are optional
                Buffering.None => null,
                _ => throw new ArgumentException("unsupported value $buffering", nameof(buffering)),
            };

            TProtocolFactory protocolFactory = protocol switch
            {
                Protocol.Binary => new TBinaryProtocol.Factory(),
                Protocol.Compact => new TCompactProtocol.Factory(),
                Protocol.Json => new TJsonProtocol.Factory(),
                _ => throw new ArgumentException("unsupported value $protocol", nameof(protocol)),
            };

            var handler = new CalculatorAsyncHandler();
            ITAsyncProcessor processor = new Calculator.AsyncProcessor(handler);

            if (multiplex)
            {
                var multiplexedProcessor = new TMultiplexedProcessor();
                multiplexedProcessor.RegisterProcessor(nameof(Calculator), processor);

                processor = multiplexedProcessor;
            }


            try
            {
                Logger.LogInformation(
                    "TSimpleAsyncServer with \n{transport} transport\n{buffering} buffering\nmultiplex = {multiplex}\n{protocol} protocol",
                    transport,
                    buffering,
                    multiplex ? "yes" : "no",
                    protocol
                    );

                var server = new TSimpleAsyncServer(
                    itProcessorFactory: new TSingletonProcessorFactory(processor),
                    serverTransport: serverTransport,
                    inputTransportFactory: transportFactory,
                    outputTransportFactory: transportFactory,
                    inputProtocolFactory: protocolFactory,
                    outputProtocolFactory: protocolFactory,
                    logger: LoggingHelper.CreateLogger <TSimpleAsyncServer>());

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

                await server.ServeAsync(cancellationToken);
            }
            catch (Exception x)
            {
                Logger.LogInformation("{x}", x);
            }
        }
Пример #2
1
        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);
                }


                TTransportFactory transFactory = null;

                // Transport
                TServerTransport trans;

                switch (param.transport)
                {
                case TransportChoice.NamedPipe:
                    Debug.Assert(param.pipe != null);
                    trans = new TNamedPipeServerTransport(param.pipe);
                    break;


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

                    transFactory = new TTransportFactory();     // framed/buffered is built into socket transports
                    trans        = new TTlsServerSocketTransport(param.port, cert, param.buffering,
                                                                 (sender, certificate, chain, errors) => true,
                                                                 null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12);
                    break;

                case TransportChoice.Socket:
                default:
                    transFactory = new TTransportFactory();     // framed/buffered is built into socket transports
                    trans        = new TServerSocketTransport(param.port, 0, param.buffering);
                    break;
                }

                // add layered transport, if not already set above
                if (transFactory == null)
                {
                    switch (param.buffering)
                    {
                    case Buffering.FramedTransport:
                        transFactory = new TFramedTransport.Factory();
                        break;

                    case Buffering.BufferedTransport:
                        transFactory = new TBufferedTransport.Factory();
                        break;
                    }
                }

                // Protocol
                ITProtocolFactory proto;
                switch (param.protocol)
                {
                case ProtocolChoice.Compact:
                    proto = new TCompactProtocol.Factory();
                    break;

                case ProtocolChoice.Json:
                    proto = new TJsonProtocol.Factory();
                    break;

                case ProtocolChoice.Binary:
                default:
                    proto = new TBinaryProtocol.Factory();
                    break;
                }

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

                TServer serverEngine = new TSimpleAsyncServer(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.buffering == Buffering.BufferedTransport ? " with buffered transport" : "") +
                                  (param.buffering == Buffering.FramedTransport ? " with framed transport" : "") +
                                  (param.transport == TransportChoice.TlsSocket ? " with encryption" : "") +
                                  (param.protocol == ProtocolChoice.Compact ? " with compact protocol" : "") +
                                  (param.protocol == ProtocolChoice.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);
        }
Пример #3
0
 public TThreadPoolServer(TProcessor processor,
                          TServerTransport serverTransport,
                          TTransportFactory inputTransportFactory,
                          TTransportFactory outputTransportFactory,
                          TProtocolFactory inputProtocolFactory,
                          TProtocolFactory outputProtocolFactory,
                          int minThreadPoolThreads, int maxThreadPoolThreads, LogDelegate logDel)
     : base(processor, serverTransport, inputTransportFactory, outputTransportFactory,
            inputProtocolFactory, outputProtocolFactory, logDel)
 {
     if (!ThreadPool.SetMaxThreads(maxThreadPoolThreads, maxThreadPoolThreads))
     {
         throw new Exception("Error: could not SetMaxThreads in ThreadPool");
     }
 }
Пример #4
0
 public TThreadedServer(TProcessorFactory processorFactory,
                        TServerTransport serverTransport,
                        TTransportFactory inputTransportFactory,
                        TTransportFactory outputTransportFactory,
                        TProtocolFactory inputProtocolFactory,
                        TProtocolFactory outputProtocolFactory,
                        int maxThreads, LogDelegate logDel)
     : base(processorFactory, serverTransport, inputTransportFactory, outputTransportFactory,
            inputProtocolFactory, outputProtocolFactory, logDel)
 {
     this.maxThreads = maxThreads;
     clientQueue     = new Queue <TTransport>();
     clientLock      = new object();
     clientThreads   = new THashSet <Thread>();
 }
Пример #5
0
        public TThreadPoolAsyncServer(ITProcessorFactory processorFactory,
                                      TServerTransport serverTransport,
                                      TTransportFactory inputTransportFactory,
                                      TTransportFactory outputTransportFactory,
                                      TProtocolFactory inputProtocolFactory,
                                      TProtocolFactory outputProtocolFactory,
                                      Configuration threadConfig,
                                      ILogger logger = null)
            : base(processorFactory, serverTransport, inputTransportFactory, outputTransportFactory,
                   inputProtocolFactory, outputProtocolFactory, logger)
        {
            lock (typeof(TThreadPoolAsyncServer))
            {
                if ((threadConfig.MaxWorkerThreads > 0) || (threadConfig.MaxIOThreads > 0))
                {
                    ThreadPool.GetMaxThreads(out int work, out int comm);
                    if (threadConfig.MaxWorkerThreads > 0)
                    {
                        work = threadConfig.MaxWorkerThreads;
                    }
                    if (threadConfig.MaxIOThreads > 0)
                    {
                        comm = threadConfig.MaxIOThreads;
                    }
                    if (!ThreadPool.SetMaxThreads(work, comm))
                    {
                        throw new Exception("Error: could not SetMaxThreads in ThreadPool");
                    }
                }

                if ((threadConfig.MinWorkerThreads > 0) || (threadConfig.MinIOThreads > 0))
                {
                    ThreadPool.GetMinThreads(out int work, out int comm);
                    if (threadConfig.MinWorkerThreads > 0)
                    {
                        work = threadConfig.MinWorkerThreads;
                    }
                    if (threadConfig.MinIOThreads > 0)
                    {
                        comm = threadConfig.MinIOThreads;
                    }
                    if (!ThreadPool.SetMinThreads(work, comm))
                    {
                        throw new Exception("Error: could not SetMinThreads in ThreadPool");
                    }
                }
            }
        }
Пример #6
0
 public TServer(TProcessor processor,
                TServerTransport serverTransport,
                TTransportFactory inputTransportFactory,
                TTransportFactory outputTransportFactory,
                TProtocolFactory inputProtocolFactory,
                TProtocolFactory outputProtocolFactory,
                LogDelegate logDelegate)
 {
     this.processor              = processor;
     this.serverTransport        = serverTransport;
     this.inputTransportFactory  = inputTransportFactory;
     this.outputTransportFactory = outputTransportFactory;
     this.inputProtocolFactory   = inputProtocolFactory;
     this.outputProtocolFactory  = outputProtocolFactory;
     this.logDelegate            = (logDelegate != null) ? logDelegate : DefaultLogDelegate;
 }
Пример #7
0
 public TSimpleAsyncServer(ITProcessorFactory itProcessorFactory,
                           TServerTransport serverTransport,
                           TTransportFactory inputTransportFactory,
                           TTransportFactory outputTransportFactory,
                           TProtocolFactory inputProtocolFactory,
                           TProtocolFactory outputProtocolFactory,
                           ILoggerFactory loggerFactory)
     : this(itProcessorFactory,
            serverTransport,
            inputTransportFactory,
            outputTransportFactory,
            inputProtocolFactory,
            outputProtocolFactory,
            loggerFactory.CreateLogger <TSimpleAsyncServer>())
 {
 }
Пример #8
0
 public TSimpleAsyncServer(ITProcessorFactory itProcessorFactory,
                           TServerTransport serverTransport,
                           TTransportFactory inputTransportFactory,
                           TTransportFactory outputTransportFactory,
                           TProtocolFactory inputProtocolFactory,
                           TProtocolFactory outputProtocolFactory,
                           ILogger logger)
     : base(itProcessorFactory,
            serverTransport,
            inputTransportFactory,
            outputTransportFactory,
            inputProtocolFactory,
            outputProtocolFactory,
            logger)
 {
 }
Пример #9
0
 public TSimpleAsyncServer(ITProcessorFactory itProcessorFactory,
                           TServerTransport serverTransport,
                           TTransportFactory inputTransportFactory,
                           TTransportFactory outputTransportFactory,
                           TProtocolFactory inputProtocolFactory,
                           TProtocolFactory outputProtocolFactory,
                           ILoggerFactory loggerFactory,
                           int clientWaitingDelay = 10)
     : this(itProcessorFactory,
            serverTransport,
            inputTransportFactory,
            outputTransportFactory,
            inputProtocolFactory,
            outputProtocolFactory,
            loggerFactory.CreateLogger <TSimpleAsyncServer>(),
            clientWaitingDelay)
 {
 }
Пример #10
0
        public void Run(int port)
        {
            try
            {
                TServerTransport transport = new TServerSocket(port);

                TTransportFactory transportFac = new TTransportFactory();

                TProtocolFactory  inputProtocolFactory = new TBinaryProtocol.Factory();
                TThreadPoolServer server = new TThreadPoolServer(getProcessorFactory(), transport, transportFac, inputProtocolFactory);

                server.Serve();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Пример #11
0
 public TSimpleAsyncServer(ITProcessorFactory itProcessorFactory,
                           TServerTransport serverTransport,
                           TTransportFactory inputTransportFactory,
                           TTransportFactory outputTransportFactory,
                           TProtocolFactory inputProtocolFactory,
                           TProtocolFactory outputProtocolFactory,
                           ILogger logger,
                           int clientWaitingDelay = 10)
     : base(itProcessorFactory,
            serverTransport,
            inputTransportFactory,
            outputTransportFactory,
            inputProtocolFactory,
            outputProtocolFactory,
            logger)
 {
     _clientWaitingDelay = clientWaitingDelay;
 }
Пример #12
0
 public TThreadPoolServer(TProcessor processor,
                          TServerTransport serverTransport,
                          TTransportFactory inputTransportFactory,
                          TTransportFactory outputTransportFactory,
                          TProtocolFactory inputProtocolFactory,
                          TProtocolFactory outputProtocolFactory,
                          int minThreadPoolThreads, int maxThreadPoolThreads, LogDelegate logDel)
     : base(processor, serverTransport, inputTransportFactory, outputTransportFactory,
            inputProtocolFactory, outputProtocolFactory, logDel)
 {
     // Can't SetMinThreads in NetStandard (?)
     //if (!ThreadPool.SetMinThreads(minThreadPoolThreads, minThreadPoolThreads))
     //{
     //	throw new Exception("Error: could not SetMinThreads in ThreadPool");
     //}
     //if (!ThreadPool.SetMaxThreads(maxThreadPoolThreads, maxThreadPoolThreads))
     //{
     //	throw new Exception("Error: could not SetMaxThreads in ThreadPool");
     //}
 }
Пример #13
0
        static void Main(string[] args)
        {
            //Start the background mock trade generator thread
            (new Thread(TradeEventGenerator.ThreadProc)).Start();

            //Create the Service Handler and Processor
            TradeStreamHandler handler = new TradeStreamHandler();

            PNWF.TradeStream.Processor proc = new PNWF.TradeStream.Processor(handler);

            //Setup the I/O stack factories
            TServerTransport  trans    = new TNamedPipeServerTransport("TradeStream");
            TTransportFactory transFac = new TTransportFactory();
            TProtocolFactory  protoFac = new TCompactProtocol.Factory();

            //Setup the server and register the event handler
            TServer server = new TThreadedServer(proc, trans, transFac, protoFac);

            server.setEventHandler(new TradeServerEventHandler());
            server.Serve();
        }
Пример #14
0
        public THttpServerTransport(
            ITAsyncProcessor processor,
            TProtocolFactory inputProtocolFactory,
            TProtocolFactory outputProtocolFactory,
            TTransportFactory inputTransFactory  = null,
            TTransportFactory outputTransFactory = null,
            RequestDelegate next         = null,
            ILoggerFactory loggerFactory = null)
        {
            // loggerFactory == null is not illegal anymore

            Processor             = processor ?? throw new ArgumentNullException(nameof(processor));
            InputProtocolFactory  = inputProtocolFactory ?? throw new ArgumentNullException(nameof(inputProtocolFactory));
            OutputProtocolFactory = outputProtocolFactory ?? throw new ArgumentNullException(nameof(outputProtocolFactory));

            InputTransportFactory  = inputTransFactory;
            OutputTransportFactory = outputTransFactory;

            _next   = next;
            _logger = (loggerFactory != null) ? loggerFactory.CreateLogger <THttpServerTransport>() : new NullLogger <THttpServerTransport>();
        }
        protected TBaseServer(ITProcessorFactory itProcessorFactory, TServerTransport serverTransport,
                              TTransportFactory inputTransportFactory, TTransportFactory outputTransportFactory,
                              ITProtocolFactory inputProtocolFactory, ITProtocolFactory outputProtocolFactory,
                              ILogger logger)
        {
            if (itProcessorFactory == null)
            {
                throw new ArgumentNullException(nameof(itProcessorFactory));
            }
            if (inputTransportFactory == null)
            {
                throw new ArgumentNullException(nameof(inputTransportFactory));
            }
            if (outputTransportFactory == null)
            {
                throw new ArgumentNullException(nameof(outputTransportFactory));
            }
            if (inputProtocolFactory == null)
            {
                throw new ArgumentNullException(nameof(inputProtocolFactory));
            }
            if (outputProtocolFactory == null)
            {
                throw new ArgumentNullException(nameof(outputProtocolFactory));
            }
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            ItProcessorFactory     = itProcessorFactory;
            ServerTransport        = serverTransport;
            InputTransportFactory  = inputTransportFactory;
            OutputTransportFactory = outputTransportFactory;
            InputProtocolFactory   = inputProtocolFactory;
            OutputProtocolFactory  = outputProtocolFactory;
            Logger = logger;
        }
Пример #16
0
        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);
        }
Пример #17
0
 public ThriftServer(TProcessor processor, TServerTransport serverTransport, TTransportFactory transportFactory, TProtocolFactory protocolFactory)
     : base(processor, serverTransport, transportFactory, protocolFactory)
 {
 }
Пример #18
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);
        }
Пример #19
0
        private async Task RunSelectedConfigurationAsync(Transport transport, Buffering buffering, Protocol protocol, bool multiplex, CancellationToken cancellationToken)
        {
            var port          = _thriftServerOption.CurrentValue.Port;
            var configuration = _thriftServerOption.CurrentValue.Configuration;
            TServerTransport serverTransport = transport switch
            {
                Transport.Tcp => new TServerSocketTransport(port, configuration),
                Transport.NamedPipe => new TNamedPipeServerTransport(".test", configuration),//, NamedPipeClientFlags.None),
                Transport.TcpTls => new TTlsServerSocketTransport(9090, configuration, GetCertificate(), ClientCertValidator, LocalCertificateSelectionCallback),
                _ => throw new ArgumentException("unsupported value $transport", nameof(transport)),
            };

            TTransportFactory transportFactory = buffering switch
            {
                Buffering.Buffered => new TBufferedTransport.Factory(),
                Buffering.Framed => new TFramedTransport.Factory(),
                // layered transport(s) are optional
                Buffering.None => null,
                _ => throw new ArgumentException("unsupported value $buffering", nameof(buffering)),
            };

            TProtocolFactory protocolFactory = protocol switch
            {
                Protocol.Binary => new TBinaryProtocol.Factory(),
                Protocol.Compact => new TCompactProtocol.Factory(),
                Protocol.Json => new TJsonProtocol.Factory(),
                Protocol.BinaryHeader => new TBinaryHeaderServerProtocol.Factory(),
                Protocol.CompactHeader => new TCompactHeaderServerProtocol.Factory(),
                Protocol.JsonHeader => new TJsonHeaderServerProtocol.Factory(),
                _ => throw new ArgumentException("unsupported value $protocol", nameof(protocol)),
            };

            //var handler = new CalculatorAsyncHandler();
            //ITAsyncProcessor processor = new Calculator.AsyncProcessor(handler);
            ITAsyncProcessor processor = _asyncProcessorList.FirstOrDefault();

            if (multiplex)
            {
                var multiplexedProcessor = new TMultiplexedProcessor();
                foreach (var item in _asyncProcessorList)
                {
                    multiplexedProcessor.RegisterProcessor(item.GetType().FullName, item);
                }

                processor = multiplexedProcessor;
            }


            try
            {
                _logger.LogInformation(
                    string.Format(
                        "TSimpleAsyncServer with \n{0} transport\n{1} buffering\nmultiplex = {2}\n{3} protocol",
                        transport,
                        buffering,
                        multiplex ? "yes" : "no",
                        protocol
                        ));


                _server = new TSimpleAsyncServer(
                    itProcessorFactory: new TSingletonProcessorFactory(processor),
                    serverTransport: serverTransport,
                    inputTransportFactory: transportFactory,
                    outputTransportFactory: transportFactory,
                    inputProtocolFactory: protocolFactory,
                    outputProtocolFactory: protocolFactory,
                    logger: _loggerFactory.CreateLogger <TSimpleAsyncServer>());

                //var threadConfig = new TThreadPoolAsyncServer.Configuration();
                //var server = new TThreadPoolAsyncServer(
                //     processorFactory: new TSingletonProcessorFactory(processor),
                //     serverTransport: serverTransport,
                //     inputTransportFactory: transportFactory,
                //     outputTransportFactory: transportFactory,
                //     inputProtocolFactory: protocolFactory,
                //     outputProtocolFactory: protocolFactory,
                //     threadConfig: threadConfig,
                //     logger: loggerFactory.CreateLogger<TThreadPoolAsyncServer>());

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

                await _server.ServeAsync(cancellationToken);
            }
            catch (Exception x)
            {
                _logger.LogInformation(x.ToString());
            }
        }
Пример #20
0
 public TServer(TProcessor processor, TServerTransport serverTransport, TTransportFactory transportFactory, TProtocolFactory protocolFactory) : this(processor, serverTransport, transportFactory, transportFactory, protocolFactory, protocolFactory, new TServer.LogDelegate(TServer.DefaultLogDelegate))
 {
 }
Пример #21
0
        private static async Task RunSelectedConfigurationAsync(Transport transport, Buffering buffering, Protocol protocol, CancellationToken cancellationToken)
        {
            var handler = new CalculatorAsyncHandler();

            TServerTransport serverTransport = null;

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

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

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

            TTransportFactory inputTransportFactory  = null;
            TTransportFactory outputTransportFactory = null;

            switch (buffering)
            {
            case Buffering.Buffered:
                inputTransportFactory  = new TBufferedTransport.Factory();
                outputTransportFactory = new TBufferedTransport.Factory();
                break;

            case Buffering.Framed:
                inputTransportFactory  = new TFramedTransport.Factory();
                outputTransportFactory = new TFramedTransport.Factory();
                break;

            default:     // layered transport(s) are optional
                Debug.Assert(buffering == Buffering.None, "unhandled case");
                break;
            }

            TProtocolFactory inputProtocolFactory  = null;
            TProtocolFactory outputProtocolFactory = null;
            ITAsyncProcessor processor             = null;

            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 CalculatorAsyncHandler();
                var calcProcessor = new Calculator.AsyncProcessor(calcHandler);

                var sharedServiceHandler   = new SharedServiceAsyncHandler();
                var sharedServiceProcessor = new SharedService.AsyncProcessor(sharedServiceHandler);

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

                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 loggerFactory = ServiceCollection.BuildServiceProvider().GetService <ILoggerFactory>();

                var server = new TSimpleAsyncServer(
                    itProcessorFactory: new TSingletonProcessorFactory(processor),
                    serverTransport: serverTransport,
                    inputTransportFactory: inputTransportFactory,
                    outputTransportFactory: outputTransportFactory,
                    inputProtocolFactory: inputProtocolFactory,
                    outputProtocolFactory: outputProtocolFactory,
                    logger: loggerFactory.CreateLogger <TSimpleAsyncServer>());

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

                await server.ServeAsync(cancellationToken);
            }
            catch (Exception x)
            {
                Logger.LogInformation(x.ToString());
            }
        }
Пример #22
0
        public static bool Execute(string[] args)
        {
            try
            {
                bool                 useBufferedSockets = false, useFramed = false, useEncryption = false, compact = false, json = false;
                ServerType           serverType           = ServerType.TSimpleServer;
                ProcessorFactoryType processorFactoryType = ProcessorFactoryType.TSingletonProcessorFactory;
                int    port = 9090;
                string pipe = null;
                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i] == "-pipe")  // -pipe name
                    {
                        pipe = args[++i];
                    }
                    else if (args[i].Contains("--port="))
                    {
                        port = int.Parse(args[i].Substring(args[i].IndexOf("=") + 1));
                    }
                    else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered")
                    {
                        useBufferedSockets = true;
                    }
                    else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed")
                    {
                        useFramed = true;
                    }
                    else if (args[i] == "--compact" || args[i] == "--protocol=compact")
                    {
                        compact = true;
                    }
                    else if (args[i] == "--json" || args[i] == "--protocol=json")
                    {
                        json = true;
                    }
                    else if (args[i] == "--threaded" || args[i] == "--server-type=threaded")
                    {
                        serverType = ServerType.TThreadedServer;
                    }
                    else if (args[i] == "--threadpool" || args[i] == "--server-type=threadpool")
                    {
                        serverType = ServerType.TThreadPoolServer;
                    }
                    else if (args[i] == "--prototype" || args[i] == "--processor=prototype")
                    {
                        processorFactoryType = ProcessorFactoryType.TPrototypeProcessorFactory;
                    }
                    else if (args[i] == "--ssl")
                    {
                        useEncryption = true;
                    }
                }

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

                TProtocolFactory proto;
                if (compact)
                {
                    proto = new TCompactProtocol.Factory();
                }
                else if (json)
                {
                    proto = new TJSONProtocol.Factory();
                }
                else
                {
                    proto = new TBinaryProtocol.Factory();
                }

                TProcessorFactory processorFactory;
                if (processorFactoryType == ProcessorFactoryType.TPrototypeProcessorFactory)
                {
                    processorFactory = new TPrototypeProcessorFactory <ThriftTest.Processor, TestHandler>();
                }
                else
                {
                    // Processor
                    TestHandler          testHandler   = new TestHandler();
                    ThriftTest.Processor testProcessor = new ThriftTest.Processor(testHandler);
                    processorFactory = new TSingletonProcessorFactory(testProcessor);
                }

                TTransportFactory transFactory;
                if (useFramed)
                {
                    transFactory = new TFramedTransport.Factory();
                }
                else
                {
                    transFactory = new TTransportFactory();
                }

                TServer serverEngine;
                switch (serverType)
                {
                case ServerType.TThreadPoolServer:
                    serverEngine = new TThreadPoolServer(processorFactory, trans, transFactory, proto);
                    break;

                case ServerType.TThreadedServer:
                    serverEngine = new TThreadedServer(processorFactory, trans, transFactory, proto);
                    break;

                default:
                    serverEngine = new TSimpleServer(processorFactory, trans, transFactory, proto);
                    break;
                }

                //Server event handler
                TradeServerEventHandler serverEvents = new TradeServerEventHandler();
                serverEngine.setEventHandler(serverEvents);

                // Run it
                string where = (pipe != null ? "on pipe " + pipe : "on port " + port);
                Console.WriteLine("Starting the " + serverType.ToString() + " " + where +
                                  (processorFactoryType == ProcessorFactoryType.TPrototypeProcessorFactory ? " with processor prototype factory " : "") +
                                  (useBufferedSockets ? " with buffered socket" : "") +
                                  (useFramed ? " with framed transport" : "") +
                                  (useEncryption ? " with encryption" : "") +
                                  (compact ? " with compact protocol" : "") +
                                  (json ? " with json protocol" : "") +
                                  "...");
                serverEngine.Serve();
            }
            catch (Exception x)
            {
                Console.Error.Write(x);
                return(false);
            }
            Console.WriteLine("done.");
            return(true);
        }
Пример #23
0
 public TSimpleServer(TProcessor processor, TServerTransport serverTransport, TTransportFactory transportFactory) : base(processor, serverTransport, transportFactory, transportFactory, new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(), new TServer.LogDelegate(TServer.DefaultLogDelegate))
 {
 }