コード例 #1
1
ファイル: TestServer.cs プロジェクト: yuzy2016/thrift
        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);
        }
コード例 #2
0
        public async void JaegerThriftIntegrationTest_TAbstractBaseGeneratesConsistentThriftPayload()
        {
            var validJaegerThriftPayload = Convert.FromBase64String("goEBCWVtaXRCYXRjaBwcGAx0ZXN0IHByb2Nlc3MZHBgQdGVzdF9wcm9jZXNzX3RhZxUAGAp0ZXN0X3ZhbHVlAAAZHBab5cuG2OehhdwBFuPakI2n2cCVLhbUpdv9yJDPo4EBFpjckNKFzqHOsgEYBE5hbWUZHBUAFpvly4bY56GF3AEW49qQjafZwJUuFpCmrOGWyrWcgwEAFQIWgICz3saWvwUWgJycORl8GAlzdHJpbmdLZXkVABgFdmFsdWUAGAdsb25nS2V5FQZGAgAYCGxvbmdLZXkyFQZGAgAYCWRvdWJsZUtleRUCJwAAAAAAAPA/ABgKZG91YmxlS2V5MhUCJwAAAAAAAPA/ABgHYm9vbEtleRUEMQAYCXNwYW4ua2luZBUAGAZjbGllbnQAGSwWgICz3saWvwUZLBgDa2V5FQAYBXZhbHVlABgHbWVzc2FnZRUAGAZFdmVudDEAABaAgLPexpa/BRksGANrZXkVABgFdmFsdWUAGAdtZXNzYWdlFQAYBkV2ZW50MgAAAAAA");

            using (var memoryTransport = new InMemoryTransport())
            {
                var protocolFactory = new TCompactProtocol.Factory();
                var thriftClient    = new JaegerThriftClient(protocolFactory.GetProtocol(memoryTransport));
                var spanData        = CreateTestSpan();
                var span            = spanData.ToJaegerSpan();
                var process         = new Process("test process", new Dictionary <string, object> {
                    { "test_process_tag", "test_value" }
                });
                var batch = new Batch(process, new List <JaegerSpan> {
                    span
                });

                await thriftClient.EmitBatchAsync(batch, CancellationToken.None);

                var buff = memoryTransport.GetBuffer();

                // all parts except spanId match (we can't control/mock span-id generation)
                Assert.Equal(validJaegerThriftPayload.AsSpan().Slice(0, 89).ToArray(), buff.AsSpan().Slice(0, 89).ToArray());
                Assert.Equal(validJaegerThriftPayload.AsSpan().Slice(98).ToArray(), buff.AsSpan().Slice(98).ToArray());

                byte [] spanIdBytes = new byte[8];
                spanData.Context.SpanId.CopyTo(spanIdBytes);

                Assert.Equal(span.SpanId, BitConverter.ToInt64(spanIdBytes, 0));

                // TODO: validate spanId in thrift payload
            }
        }
コード例 #3
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);
        }
コード例 #4
0
        public static void Run()
        {
            TServerTransport serverTransport = new TServerSocket(8005);

            TTransportFactory transportFactory = new TTransportFactory();

            TProtocolFactory protocolFactory = new TCompactProtocol.Factory();

            var processor = new IUserService.Processor(new UserService());

            var server = new TThreadPoolServer(processor, serverTransport, transportFactory, protocolFactory);

            server.Serve();
        }
コード例 #5
0
        public JaegerExporter(JaegerOptions options)
        {
            var protocolFactory = new TCompactProtocol.Factory();

            _options = options;
            _maxPayloadSizeInBytes = options.MaxPayloadSizeInBytes;
            _clientTransport       = new JaegerThriftClientTransport(options.Host, options.Port, new MemoryStream(), options.TransportClient);
            _thriftClient          = new JaegerThriftClient(protocolFactory.GetProtocol(_clientTransport));
            _memoryTransport       = new InMemoryTransport(16000);
            _memoryProtocol        = protocolFactory.GetProtocol(_memoryTransport);
            _serviceName           = options.ServiceName;

            Process = new Process(_serviceName);
        }
コード例 #6
0
        private static int CalcSizeOfSerializedThrift(TBase thriftBase)
        {
            var thriftBuffer    = new TMemoryBuffer();
            var protocolFactory = new TCompactProtocol.Factory();
            var thriftProtocol  = protocolFactory.GetProtocol(thriftBuffer);

            try
            {
                thriftBase.WriteAsync(thriftProtocol, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult();
            }
            catch (Exception e)
            {
                throw new Exception("failed to calculate the size of a serialized thrift object", e);
            }
            return(thriftBuffer.GetBuffer().Length);
        }
コード例 #7
0
ファイル: Program.cs プロジェクト: xydoublez/thriftDemoCSharp
        static void Main()
        {
            //TServerSocket serverTransport = new TServerSocket(new System.Net.Sockets.TcpListener(IPAddress.Parse("192.168.43.1"), 25000));
            TServerSocket serverTransport = new TServerSocket(25001, 0, false);
            //异步IO,需要使用TFramedTransport,它将分块缓存读取
            var tfactory = new TFramedTransport.Factory();
            //使用高密度二进制协议
            var pfactory = new TCompactProtocol.Factory();
            TMultiplexedProcessor processor = new TMultiplexedProcessor();

            com.msunsoft.service.calculator.Processor calcProcessor = new com.msunsoft.service.calculator.Processor(new Server());
            processor.RegisterProcessor("test-server-rpc$com.msunsoft.service.calculator$2.0", calcProcessor);
            TThreadedServer server = new TThreadedServer(processor, serverTransport, tfactory, pfactory);

            Console.WriteLine("Starting server on port 25001 ...");
            server.Serve();
        }
コード例 #8
0
        public async Task JaegerThriftIntegrationTest_TAbstractBaseGeneratesConsistentThriftPayload()
        {
            var validJaegerThriftPayload = Convert.FromBase64String(TestPayloadBase64);

            using var memoryTransport = new InMemoryTransport();
            var protocolFactory = new TCompactProtocol.Factory();
            var thriftClient    = new JaegerThriftClient(protocolFactory.GetProtocol(memoryTransport));
            var spanData        = CreateTestSpan();
            var span            = spanData.ToJaegerSpan();
            var process         = TestProcess;
            var batch           = new Batch(process, new List <JaegerSpan> {
                span
            });

            await thriftClient.EmitBatchAsync(batch, CancellationToken.None);

            Assert.Equal(validJaegerThriftPayload, memoryTransport.ToArray());
        }
コード例 #9
0
ファイル: tradeServer.cs プロジェクト: superdjz/ThriftBook
        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();
        }
コード例 #10
0
        public async void EmitBatchOverhead_ShouldNotGoOverOverheadConstant()
        {
            var transport       = new TMemoryBuffer();
            var protocolFactory = new TCompactProtocol.Factory();
            var client          = new Agent.Client(protocolFactory.GetProtocol(transport));

            var jSpan     = new JaegerSpan(10, 11, 12, 13, "opName", 0, 1234, 1235);
            var jSpanSize = CalcSizeOfSerializedThrift(jSpan);

            var tests = new[] { 1, 2, 14, 15, 377, 500, 65000, 0xFFFF };

            foreach (var test in tests)
            {
                transport.Reset();
                var batch       = new List <JaegerSpan>();
                var processTags = new List <JaegerTag>();
                for (var j = 0; j < test; j++)
                {
                    batch.Add(jSpan);
                    processTags.Add(new JaegerTag("testingTag", TagType.BINARY)
                    {
                        VBinary = new byte[] { 0x20 }
                    });
                }

                var jProcess = new JaegerProcess("testing")
                {
                    Tags = processTags
                };
                await client.emitBatchAsync(new JaegerBatch(jProcess, batch), CancellationToken.None);

                var jProcessSize = CalcSizeOfSerializedThrift(jProcess);

                var overhead = transport.GetBuffer().Length - test * jSpanSize - jProcessSize;
                Assert.True(overhead <= TransportConstants.UdpEmitBatchOverhead);
            }
        }
コード例 #11
0
        public async void JaegerThriftIntegrationTest_TAbstractBaseGeneratesConsistentThriftPayload()
        {
            var validJaegerThriftPayload = Convert.FromBase64String("goEBCWVtaXRCYXRjaBwcGAx0ZXN0IHByb2Nlc3MZHBgQdGVzdF9wcm9jZXNzX3RhZxUAGAp0ZXN0X3ZhbHVlAAAZHBab5cuG2OehhdwBFuPakI2n2cCVLhbUpdv9yJDPo4EBFpjckNKFzqHOsgEYBE5hbWUZHBUAFpvly4bY56GF3AEW49qQjafZwJUuFpCmrOGWyrWcgwEAFQIWgICz3saWvwUWgJycORl8GAlzdHJpbmdLZXkVABgFdmFsdWUAGAdsb25nS2V5FQZGAgAYCGxvbmdLZXkyFQZGAgAYCWRvdWJsZUtleRUCJwAAAAAAAPA/ABgKZG91YmxlS2V5MhUCJwAAAAAAAPA/ABgHYm9vbEtleRUEMQAYCXNwYW4ua2luZBUAGAZjbGllbnQAGSwWgICz3saWvwUZLBgDa2V5FQAYBXZhbHVlABgLZGVzY3JpcHRpb24VABgGRXZlbnQxAAAWgICz3saWvwUZLBgDa2V5FQAYBXZhbHVlABgLZGVzY3JpcHRpb24VABgGRXZlbnQyAAAAAAA=");

            using (var memoryTransport = new InMemoryTransport())
            {
                var protocolFactory = new TCompactProtocol.Factory();
                var thriftClient    = new JaegerThriftClient(protocolFactory.GetProtocol(memoryTransport));
                var spanData        = CreateTestSpan();
                var span            = spanData.ToJaegerSpan();
                var process         = new Process("test process", new Dictionary <string, object> {
                    { "test_process_tag", "test_value" }
                });
                var batch = new Batch(process, new List <JaegerSpan> {
                    span
                });

                await thriftClient.EmitBatchAsync(batch, CancellationToken.None);

                var buff = memoryTransport.GetBuffer();

                Assert.Equal(validJaegerThriftPayload, buff);
            }
        }
コード例 #12
0
        public async void JaegerThriftIntegrationTest_TAbstractBaseGeneratesConsistentThriftPayload()
        {
            var validJaegerThriftPayload = Convert.FromBase64String("goEBCWVtaXRCYXRjaBwcGAx0ZXN0IHByb2Nlc3MZHBgQdGVzdF9wcm9jZXNzX3RhZxUAGAp0ZXN0X3ZhbHVlAAAZHBbdlZjkk/C0+ZoBFtCr96fz8ZbpnQEW1KXb/ciQz6OBARaY3JDShc6hzrIBGAROYW1lGRwVABbdlZjkk/C0+ZoBFtCr96fz8ZbpnQEWkKas4ZbKtZyDAQAVAhaAgLPexpa/BRaAnJw5GWwYCXN0cmluZ0tleRUAGAV2YWx1ZQAYB2xvbmdLZXkVBkYCABgIbG9uZ0tleTIVBkYCABgJZG91YmxlS2V5FQInAAAAAAAA8D8AGApkb3VibGVLZXkyFQInAAAAAAAA8D8AGAdib29sS2V5FQQxABksFoCAs97Glr8FGSwYA2tleRUAGAV2YWx1ZQAYC2Rlc2NyaXB0aW9uFQAYBkV2ZW50MQAAFoCAs97Glr8FGSwYA2tleRUAGAV2YWx1ZQAYC2Rlc2NyaXB0aW9uFQAYBkV2ZW50MgAAAAAA");

            using (var memoryTransport = new InMemoryTransport())
            {
                var protocolFactory = new TCompactProtocol.Factory();
                var thriftClient    = new JaegerThriftClient(protocolFactory.GetProtocol(memoryTransport));
                var spanData        = CreateTestSpan();
                var span            = spanData.ToJaegerSpan();
                var process         = new Process("test process", new Dictionary <string, object> {
                    { "test_process_tag", "test_value" }
                });
                var batch = new Batch(process, new List <JaegerSpan> {
                    span
                });

                await thriftClient.EmitBatchAsync(batch, CancellationToken.None);

                var buff = memoryTransport.GetBuffer();

                Assert.Equal(validJaegerThriftPayload, buff);
            }
        }
コード例 #13
0
        public async void JaegerThriftIntegrationTest_TAbstractBaseGeneratesConsistentThriftPayload()
        {
            var validJaegerThriftPayload = Convert.FromBase64String("goEBCWVtaXRCYXRjaBwcGAx0ZXN0IHByb2Nlc3MZHBgQdGVzdF9wcm9jZXNzX3RhZxUAGAp0ZXN0X3ZhbHVlAAAZHBab5cuG2OehhdwBFuPakI2n2cCVLhaAjfWp6NHt6dQBFrK5moSni5GXGBgETmFtZRkcFQAWm+XLhtjnoYXcARbj2pCNp9nAlS4W/Y6j+bqS9fbuAQAVAhaAgLPexpa/BRaAnJw5GXwYCXN0cmluZ0tleRUAGAV2YWx1ZQAYB2xvbmdLZXkVBkYCABgIbG9uZ0tleTIVBkYCABgJZG91YmxlS2V5FQInAAAAAAAA8D8AGApkb3VibGVLZXkyFQInAAAAAAAA8D8AGAdib29sS2V5FQQxABgJc3Bhbi5raW5kFQAYBmNsaWVudAAZLBaAgLPexpa/BRksGANrZXkVABgFdmFsdWUAGAdtZXNzYWdlFQAYBkV2ZW50MQAAFoCAs97Glr8FGSwYA2tleRUAGAV2YWx1ZQAYB21lc3NhZ2UVABgGRXZlbnQyAAAAAAA=");

            using (var memoryTransport = new InMemoryTransport())
            {
                var protocolFactory = new TCompactProtocol.Factory();
                var thriftClient    = new JaegerThriftClient(protocolFactory.GetProtocol(memoryTransport));
                var spanData        = CreateTestSpan();
                var span            = spanData.ToJaegerSpan();
                var process         = new Process("test process", new Dictionary <string, object> {
                    { "test_process_tag", "test_value" }
                });
                var batch = new Batch(process, new List <JaegerSpan> {
                    span
                });

                await thriftClient.EmitBatchAsync(batch, CancellationToken.None);

                var buff = memoryTransport.GetBuffer();

                Assert.Equal(validJaegerThriftPayload, buff);
            }
        }
コード例 #14
0
        /// <param name="protocolType">Protocol type (compact or binary)</param<
        /// <param name="maxPacketSize">If 0 it will use default value <see cref="ThriftUdpTransport.MAX_PACKET_SIZE"/>.</param>
        public ThriftSenderBase(ProtocolType protocolType, int maxPacketSize)
        {
            switch (protocolType)
            {
            case ProtocolType.Binary:
                ProtocolFactory = new TBinaryProtocol.Factory();
                break;

            case ProtocolType.Compact:
                ProtocolFactory = new TCompactProtocol.Factory();
                break;

            default:
                throw new NotSupportedException("Unknown thrift protocol type specified: " + protocolType);
            }

            if (maxPacketSize == 0)
            {
                maxPacketSize = ThriftUdpClientTransport.MaxPacketSize;
            }

            MaxSpanBytes     = maxPacketSize - EmitBatchOverhead;
            _memoryTransport = new TMemoryBuffer();
        }
コード例 #15
0
ファイル: Program.cs プロジェクト: SylarLin520/tcpIpServer
        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());
            }
        }
コード例 #16
0
ファイル: TestServer.cs プロジェクト: SylarLin520/tcpIpServer
        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);
        }
コード例 #17
0
ファイル: Program.cs プロジェクト: kaanid/ThriftDome
        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);
            }
        }
コード例 #18
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);
        }
コード例 #19
0
        } // class TestHandler

        public static bool Execute(string[] args)
        {
            try
            {
                bool   useBufferedSockets = false, useFramed = false, useEncryption = false, compact = false, json = false;
                int    port = 9090;
                string pipe = null;
                string certPath = "../../../../../keys/server.pem";
                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] == "--ssl")
                    {
                        useEncryption = true;
                    }
                    else if (args[i].StartsWith("--cert="))
                    {
                        certPath = args[i].Substring("--cert=".Length);
                    }
                }

                // Processor
                TestHandler          testHandler   = new TestHandler();
                ThriftTest.Processor testProcessor = new ThriftTest.Processor(testHandler);

                // Transport
                TServerTransport trans;
                if (pipe != null)
                {
                    trans = new TNamedPipeServerTransport(pipe);
                }
                else
                {
                    if (useEncryption)
                    {
                        trans = new TTLSServerSocket(port, 0, useBufferedSockets, new X509Certificate2(certPath));
                    }
                    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();
                }

                // Simple Server
                TServer serverEngine;
                if (useFramed)
                {
                    serverEngine = new TSimpleServer(testProcessor, trans, new TFramedTransport.Factory(), proto);
                }
                else
                {
                    serverEngine = new TSimpleServer(testProcessor, trans, new TTransportFactory(), proto);
                }

                // ThreadPool Server
                // serverEngine = new TThreadPoolServer(testProcessor, tServerSocket);

                // Threaded Server
                // serverEngine = new TThreadedServer(testProcessor, tServerSocket);

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

                testHandler.server = serverEngine;

                // Run it
                string where = (pipe != null ? "on pipe " + pipe : "on port " + port);
                Console.WriteLine("Starting the server " + where +
                                  (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);
        }
コード例 #20
0
ファイル: TestServer.cs プロジェクト: yangjiandan/thrift
        }         // class TestHandler

        public static void Execute(string[] args)
        {
            try
            {
                bool   useBufferedSockets = false, useFramed = false, useEncryption = false, compact = false, json = false;
                int    port = 9090, i = 0;
                string pipe = null;
                if (args.Length > 0)
                {
                    i = 0;
                    if (args[i] == "-pipe")                      // -pipe name
                    {
                        pipe = args[++i];
                    }
                    else                      // default to port number (compatibility)
                    {
                        port = int.Parse(args[i]);
                    }

                    ++i;
                    if (args.Length > i)
                    {
                        if (args[i] == "raw")
                        {
                            // as default
                        }
                        else if (args[i] == "buffered")
                        {
                            useBufferedSockets = true;
                        }
                        else if (args[i] == "framed")
                        {
                            useFramed = true;
                        }
                        else if (args[i] == "ssl")
                        {
                            useEncryption = true;
                        }
                        else if (args[i] == "compact")
                        {
                            compact = true;
                        }
                        else if (args[i] == "json")
                        {
                            json = true;
                        }
                        else
                        {
                            // Fall back to the older boolean syntax
                            bool.TryParse(args[i], out useBufferedSockets);
                        }
                    }
                }

                // Processor
                TestHandler          testHandler   = new TestHandler();
                ThriftTest.Processor testProcessor = new ThriftTest.Processor(testHandler);

                // Transport
                TServerTransport trans;
                if (pipe != null)
                {
                    trans = new TNamedPipeServerTransport(pipe);
                }
                else
                {
                    if (useEncryption)
                    {
                        trans = new TTLSServerSocket(port, 0, useBufferedSockets, new X509Certificate2("../../../../../keys/server.pem"));
                    }
                    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();
                }

                // Simple Server
                TServer serverEngine;
                if (useFramed)
                {
                    serverEngine = new TSimpleServer(testProcessor, trans, new TFramedTransport.Factory(), proto);
                }
                else
                {
                    serverEngine = new TSimpleServer(testProcessor, trans, new TTransportFactory(), proto);
                }

                // ThreadPool Server
                // serverEngine = new TThreadPoolServer(testProcessor, tServerSocket);

                // Threaded Server
                // serverEngine = new TThreadedServer(testProcessor, tServerSocket);

                testHandler.server = serverEngine;

                // Run it
                string where = (pipe != null ? "on pipe " + pipe : "on port " + port);
                Console.WriteLine("Starting the server " + where +
                                  (useBufferedSockets ? " with buffered socket" : "") +
                                  (useFramed ? " with framed transport" : "") +
                                  (useEncryption ? " with encryption" : "") +
                                  (compact ? " with compact protocol" : "") +
                                  "...");
                serverEngine.Serve();
            }
            catch (Exception x)
            {
                Console.Error.Write(x);
            }
            Console.WriteLine("done.");
        }
コード例 #21
0
ファイル: Program.cs プロジェクト: yuzy2016/thrift
        private static async Task RunSelectedConfigurationAsync(Transport transport, Protocol protocol, CancellationToken cancellationToken)
        {
            var handler = new CalculatorAsyncHandler();
            ITAsyncProcessor processor = null;

            TServerTransport serverTransport = null;

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

            case Transport.TcpBuffered:
                serverTransport = new TServerSocketTransport(port: 9090, clientTimeout: 10000, buffering: Buffering.BufferedTransport);
                break;

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

            case Transport.TcpTls:
                serverTransport = new TTlsServerSocketTransport(9090, GetCertificate(), Buffering.None, 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 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 fabric = ServiceCollection.BuildServiceProvider().GetService <ILoggerFactory>();
                var server = new TSimpleAsyncServer(processor, serverTransport, inputProtocolFactory, outputProtocolFactory, fabric);

                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
        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.");
        }
コード例 #24
0
        public static bool Execute(string[] args)
        {
            try
            {
                bool useBufferedSockets = false, useFramed = false, useEncryption = false, compact = false, json = false;
                int  port = 9090;

                string pipe     = null;
                string certPath = "";
                var    dic = Common.GetArgs(args);
                if (dic.ContainsKey("pipe"))
                {
                    pipe = dic["pipe"];
                }

                if (dic.ContainsKey("port"))
                {
                    port = int.Parse(dic["port"]);
                }

                if (dic.ContainsKey("b") || dic.ContainsKey("buffered"))
                {
                    useBufferedSockets = true;
                }

                if (dic.ContainsKey("f") || dic.ContainsKey("framed"))
                {
                    useFramed = true;
                }

                if (dic.ContainsKey("protocol"))
                {
                    compact = dic["protocol"] == "compact";
                    json    = dic["protocol"] == "json";
                }

                if (dic.ContainsKey("ssl"))
                {
                    useEncryption = true;
                }

                if (dic.ContainsKey("cert"))
                {
                    certPath = dic["cert"];
                }



                // Processor
                DemoServiceImpl          demoService   = new DemoServiceImpl();
                RPCDemoService.Processor demoProcessor = new RPCDemoService.Processor(demoService);

                // Transport
                TServerTransport trans;
                if (pipe != null)
                {
                    trans = new TNamedPipeServerTransport(pipe);
                }
                else
                {
                    if (useEncryption)
                    {
                        trans = new TTLSServerSocket(port, 0, useBufferedSockets, new X509Certificate2(certPath));
                    }
                    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();
                }

                // Simple Server
                TServer serverEngine;
                if (useFramed)
                {
                    serverEngine = new ThriftServer(demoProcessor, trans, new TFramedTransport.Factory(), proto);
                }
                else
                {
                    serverEngine = new ThriftServer(demoProcessor, trans, new TTransportFactory(), proto);
                }

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


                // Run it
                string where = (pipe != null ? "on pipe " + pipe : "on port " + port);
                Console.WriteLine("Starting the server " + where +
                                  (useBufferedSockets ? " with buffered socket" : "") +
                                  (useFramed ? " with framed transport" : "") +
                                  (useEncryption ? " with encryption" : "") +
                                  (compact ? " with compact protocol" : "") +
                                  (json ? " with json protocol" : "") +
                                  "...");

                Console.WriteLine("Thrift Service started. Press Ctrl+C to shut down.");
                (serverEngine as IServer).Start();
            }
            catch (Exception x)
            {
                Console.Error.Write(x);
                return(false);
            }
            Console.WriteLine("done.");
            return(true);
        }