Ejemplo n.º 1
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);
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            try
            {
                //设置服务端口为8080
                TServerSocket serverTransport = new TServerSocket(9081);

                //设置传输协议工厂
                TBinaryProtocol.Factory factory = new TBinaryProtocol.Factory();

                //关联处理器与服务的实现
                TProcessor helloProcessor  = new HelloService.Processor(new MyHelloService());
                TProcessor schoolProcessor = new SchoolService.Processor(new MySchoolService());

                //创建服务端对象
                var processorMulti = new TMultiplexedProcessor();
                processorMulti.RegisterProcessor("helloService", helloProcessor);
                processorMulti.RegisterProcessor("schoolService", schoolProcessor);
                TServer server = new TThreadPoolServer(processorMulti, serverTransport, new TTransportFactory(), factory);

                Console.WriteLine("服务端正在监听9081端口");

                server.Serve();
            }
            catch (TTransportException ex)//捕获异常信息
            {
                //打印异常信息
                Console.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            try
            {
                int ServerPort = int.Parse(System.Configuration.ConfigurationManager.AppSettings["ThriftServerPort"]);
                //设置服务端口
                TServerSocket serverTransport = new TServerSocket(ServerPort);

                //设置传输协议工厂
                TBinaryProtocol.Factory factory = new TBinaryProtocol.Factory();

                //关联处理器与服务的实现
                TProcessor processor = new QuesService.Processor(new Question());

                //创建服务端对象
                TServer server = new TThreadPoolServer(processor, serverTransport, new TTransportFactory(), factory);

                Console.WriteLine("试题服务端正在监听" + ServerPort + "端口");
                server.Serve();

                Console.ReadLine();
            }
            catch (TTransportException ex)
            {
                //打印异常信息
                Console.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 4
0
        /**
         * 获取手机屏幕分辨率
         **/
        public static String sendPoint(Int32 port, Int32 x, Int32 y)
        {
            TSocket socket = new TSocket("127.0.0.1", port, 1000);

            TFramedTransport.Factory factory = new
                                               TFramedTransport.Factory();
            TTransport transport = factory.GetTransport(socket);

            TBinaryProtocol.Factory factory1 =
                new TBinaryProtocol.Factory();
            TProtocol            protocol = factory1.GetProtocol(transport);
            TMultiplexedProtocol impl1
                = new TMultiplexedProtocol(protocol, "ScreenService");

            ScreenService.Client client =
                new ScreenService.Client(impl1);
            try
            {
                socket.Open();
                return(client.sendPoint(x, y));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }
            finally
            {
                transport.Close();
            }
            return("");
        }
Ejemplo n.º 5
0
        /**
         * 点击事件
         **/
        public static void InputEvent(Int32 port, MouseEventType type)
        {
            TSocket socket = new TSocket("127.0.0.1", port, 1000);

            TFramedTransport.Factory factory = new
                                               TFramedTransport.Factory();
            TTransport transport = factory.GetTransport(socket);

            TBinaryProtocol.Factory factory1 =
                new TBinaryProtocol.Factory();
            TProtocol            protocol = factory1.GetProtocol(transport);
            TMultiplexedProtocol impl1
                = new TMultiplexedProtocol(protocol, "ScreenService");

            ScreenService.Client client =
                new ScreenService.Client(impl1);
            try
            {
                socket.Open();
                bool r
                    = client.InputEvent(type);
            }
            catch (Exception x)
            {
                Console.WriteLine(x.StackTrace);
            }
            finally
            {
                transport.Close();
            }
        }
Ejemplo n.º 6
0
 /// <summary>
 /// 要注册的服务器列表,注意一个服务只能注册一次,否则会失败(port不能重复注册)
 /// </summary>
 /// <param name="servers"></param>
 public void Register(SuperGMSServer[] servers)
 {
     try
     {
         if (servers == null || servers.Length < 1)
         {
             throw new Exception("no Server can Register");
         }
         foreach (SuperGMSServer s in servers)
         {
             TServerSocket           serverTransport = new TServerSocket(s.Config.Port);
             TBinaryProtocol.Factory factory         = new TBinaryProtocol.Factory();//传输协议
             TProcessor processor = new ThriftService.Processor(s.Server);
             TServer    server    = new TThreadPoolServer(processor, serverTransport, new TTransportFactory(), factory);
         }
     }
     catch (TTransportException tex)
     {
         //等log组件改造完之后再记录
     }
     catch (Exception ex)
     {
         //等log组件改造完之后再记录
     }
 }
Ejemplo n.º 7
0
        public static string RemoveProcess(Int32 port, String lineNumber)
        {
            TSocket socket = new TSocket("127.0.0.1", port, 3000);

            TFramedTransport.Factory factory = new
                                               TFramedTransport.Factory();
            TTransport transport = factory.GetTransport(socket);

            TBinaryProtocol.Factory factory1 =
                new TBinaryProtocol.Factory();
            TProtocol            protocol = factory1.GetProtocol(transport);
            TMultiplexedProtocol impl1
                = new TMultiplexedProtocol(protocol, "NodeService");

            NodeService.Client client =
                new NodeService.Client(impl1);
            try
            {
                socket.Open();
                return(client.RemoveProcess(lineNumber));
            }
            catch (Exception x)
            {
                Console.WriteLine(x.StackTrace);
            }
            finally
            {
                transport.Close();
            }
            return("");
        }
Ejemplo n.º 8
0
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            var msg = (ThriftMessage)message;
            var bp  = new TBinaryProtocol.Factory();
            var t   = new TThriftTransport(context.Channel, msg.Content, ThriftTransportType.Framed);
            var tp  = bp.GetProtocol(t);
            var mh  = tp.ReadMessageBegin();

            tp.ReadMessageEnd();
            var buf = msg.Content;

            byte[] req = new byte[buf.ReadableBytes];
            buf.ReadBytes(req);
            //ReadOnlySpan<byte> bytesBuffer = req;
            //ReadOnlySpan<sbyte> sbytesBuffer = MemoryMarshal.Cast<byte, sbyte>(bytesBuffer);
            //sbyte[] signed = sbytesBuffer.ToArray();
            string body = Encoding.UTF8.GetString(req);

            Trace.WriteLine($"recv order: {body}");
            string      currentTime = string.Compare(body, "query time", true) == 0 ? DateTime.Now.ToLongTimeString() : "bad order";
            IByteBuffer resp        = Unpooled.CopiedBuffer(currentTime, Encoding.UTF8);

            context.WriteAsync(resp);
            //string body = new string(signed, 0, req.Length, Encoding.UTF8);
            //base.ChannelRead(context, message);
        }
Ejemplo n.º 9
0
        static void Main(string[] args)
        {
            try
            {
                //MathServiceImpl handler = new MathServiceImpl();
                //MathService.Processor processor = new MathService.Processor(handler);
                //TServerTransport serverTransport = new TServerSocket(8088);
                //TServer server = new TSimpleServer(processor, serverTransport);
                //Console.WriteLine("Starting the server...");
                //server.Serve();

                TServerSocket serverTransport = new TServerSocket(8088);    // 设置服务端口为8088
                //Factory factory = new Factory();    // 设置协议工厂为 TBinaryProtocol
                TBinaryProtocol.Factory factory          = new TBinaryProtocol.Factory();
                TTransportFactory       transportFactory = new TTransportFactory();
                TProcessor processor = new MathService.Processor(new MathServiceImpl());
                TServer    server    = new TThreadPoolServer(processor, serverTransport, transportFactory, factory);
                Console.WriteLine($"Starting the server");
                server.Serve();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
            Console.WriteLine("Done.");
        }
Ejemplo n.º 10
0
        static void Execute(int port)
        {
            try
            {
                // create protocol factory, default to BinaryProtocol
                TProtocolFactory  ProtocolFactory  = new TBinaryProtocol.Factory(true, true);
                TServerTransport  servertrans      = new TServerSocket(port, 0, false);
                TTransportFactory TransportFactory = new TFramedTransport.Factory();

                BenchmarkService.Iface benchHandler   = new BenchmarkServiceImpl();
                TProcessor             benchProcessor = new BenchmarkService.Processor(benchHandler);

                Aggr.Iface aggrHandler   = new AggrServiceImpl();
                TProcessor aggrProcessor = new Aggr.Processor(aggrHandler);

                TMultiplexedProcessor multiplex = new TMultiplexedProcessor();
                multiplex.RegisterProcessor(Constants.NAME_BENCHMARKSERVICE, benchProcessor);
                multiplex.RegisterProcessor(Constants.NAME_AGGR, aggrProcessor);

                TServer ServerEngine = new TSimpleServer(multiplex, servertrans, TransportFactory, ProtocolFactory);

                Console.WriteLine("Starting the server ...");
                ServerEngine.Serve();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Ejemplo n.º 11
0
            protected override void InitChannel(TcpSocketChannel channel)
            {
                var pf = new TBinaryProtocol.Factory();

                channel.Pipeline.AddLast("thrift-msg-dec", new ThriftMessageDecoder(pf));
                channel.Pipeline.AddLast("thrift-msg-enc", new ThriftMessageEncoder());
                channel.Pipeline.AddLast(new ThriftServerHandler());
            }
        public PElementHostedService()
        {
            var protoFactory = new TBinaryProtocol.Factory();
            var transFactory = new TBufferedTransport.Factory();
            var handler      = new PElementServiceImplementation();
            var processor    = new PElementService.AsyncProcessor(handler);

            var transport = new TServerSocketTransport(5550, new TConfiguration());

            server = new TThreadPoolAsyncServer(processor, transport, transFactory, protoFactory);
        }
Ejemplo n.º 13
0
        public Task StartAsync(CancellationToken cancellationToken)
        {
            TServerTransport serverTransport = new TServerSocketTransport(Configuration.GetValue <int>("RpcPort"));

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

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

            return(server.ServeAsync(cancellationToken));
        }
Ejemplo n.º 14
0
        static internal void Run(int port)
        {
            // check whether the port is free
            TServerTransport serverTransport = new TServerSocket(port);

            serverTransport.Listen();
            serverTransport.Close();
            serverTransport = new TServerSocket(port);

            // one processor to rule them all
            var multiplexProcessor = new TMultiplexedProcessor();

            // create protocol factory, default to "framed binary"
            TProtocolFactory  protocolFactory  = new TBinaryProtocol.Factory(true, true);
            TTransportFactory transportFactory = new TFramedTransport.Factory();

            // create handler/processor for the public service
            Handler handler = new Handler();

            Pizzeria.Processor pizzeria = new Pizzeria.Processor(handler);
            multiplexProcessor.RegisterProcessor(typeof(Pizzeria).Name, pizzeria);

            // create handler/processor for the internal service
            // handler = same
            PizzeriaCallback.Processor callback = new PizzeriaCallback.Processor(handler);
            multiplexProcessor.RegisterProcessor(typeof(PizzeriaCallback).Name, callback);

            // create handler/processor for the diagnostics service
            // handler = same
            Diagnostics.Diagnostics.Processor diagnose = new Diagnostics.Diagnostics.Processor(handler);
            multiplexProcessor.RegisterProcessor(typeof(Diagnostics.Diagnostics).Name, diagnose);

            // more processors as needed ...

            // complete internal setup
            Console.Title = Environment.MachineName + "-" + port.ToString();

            ReadinessHttpServer.Start(PizzaConfig.ReadinessPorts.Pizzeria);
            try
            {
                // return the server instance
                //var server = new TThreadPoolServer(multiplexProcessor, serverTransport, transportFactory, protocolFactory);
                var server = new TThreadedServer(multiplexProcessor, serverTransport, transportFactory, protocolFactory);
                //var server = new TSimpleServer(multiplexProcessor, serverTransport, transportFactory, protocolFactory);

                ReadinessHttpServer.Status = Readiness.AliveAndReady;
                server.Serve();
            }
            finally
            {
                ReadinessHttpServer.Stop();
            }
        }
Ejemplo n.º 15
0
        static void Main(string[] args)
        {
            TBinaryProtocol.Factory factory         = new TBinaryProtocol.Factory();
            TServerSocket           serverTransport = new TServerSocket(7912, 0, false);

            IAgent.Processor processor = new IAgent.Processor(new AgentImpl());
            //TServer server1 = new TSimpleServer(processor, serverTransport);
            TServer server = new TThreadPoolServer(processor, serverTransport, new TTransportFactory(), factory);



            Console.WriteLine("Starting server on port 7912 ...");
            server.Serve();
        }
Ejemplo n.º 16
0
        public void startExtension(string name, string version, string sdkVersion, string minSdkVersion)
        {
            ExtensionManager.Client client = new ClientManager(EXTENSION_SOCKET).getClient();
            InternalExtensionInfo   info   = new InternalExtensionInfo {
                Name = name, Version = version, Sdk_version = sdkVersion, Min_sdk_version = minSdkVersion
            };

            try
            {
                client.OutputProtocol.Transport.Open();
                ExtensionStatus status = client.registerExtension(info, registry);
                if (status.Code == 0)
                {
                    this.uuid = status.Uuid;
                    var    processor        = new ExtensionManager.Processor(this);
                    String serverSocketPath = EXTENSION_SOCKET + "." + uuid.ToString();

                    if (File.Exists(serverSocketPath))
                    {
                        File.Delete(serverSocketPath);
                    }
                    //TODO: uncomment below

                    //var socket1 = new UnixEndPoint(EXTENSION_SOCKET);
                    var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);

                    //var listener = new TcpListener(IPAddress.Any, 9090);
                    //TServerSocket transport = new TServerSocket(9090);
                    TTransportFactory transportFactory = new TTransportFactory();
                    TProtocolFactory  protocolFactory  = new TBinaryProtocol.Factory();

                    TServerTransport serverTransport = new TNamedPipeServerTransport(serverSocketPath);
                    TTransport       trans           = client.InputProtocol.Transport;
                    TServer          server          = new TSimpleServer(processor, serverTransport, transportFactory, protocolFactory);
                    server.Serve(); //Starting the server
                }
                else
                {
                    throw new ExtensionException {
                              Code = 1, Message = status.Message, Uuid = uuid ?? -1
                    };
                }
            }
            catch (TException e)
            {
                throw new ExtensionException {
                          Code = 1, Message = "Could not connect to socket", Uuid = uuid ?? -1
                };
            }
        }
Ejemplo n.º 17
0
        public void StartServer()
        {
            try
            {
                var configuration = GetConfiguration();
                Log.Logger = CreateSerilogLogger(configuration);
                IHost host       = CreateHostBuilder(configuration, Log.Logger);
                int   serverPort = configuration.GetValue <int>(STR_ThriftServerDefaultPort);

                Log.Information("Starting {0} at port {1}", STR_AppName, serverPort);

                //Prepare the thrift server processor
                ThriftGatewayServerImpl serverHandler = new ThriftGatewayServerImpl();
                var processor = new ThriftAPIGatewayService.AsyncProcessor(serverHandler);

                var protocolFactory     = new TBinaryProtocol.Factory();
                var thriftConfiguration = new TConfiguration();
                var serverTransport     = new TServerSocketTransport(serverPort, thriftConfiguration);
                var transportFactory    = new TBufferedTransport.Factory();
                var threadConfiguration = new TThreadPoolAsyncServer.Configuration();
                var loggerFactory       = new SerilogLoggerFactory(Log.Logger);

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

                Log.Information("Starting {0} at port {1}", STR_AppName, serverPort);
                Log.Information(STR_QuitText);

                var source = new CancellationTokenSource();
                server.ServeAsync(CancellationToken.None).GetAwaiter().GetResult();
                Console.ReadLine();
                source.Cancel();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Startup terminated unexpectedly ({ApplicationContext})!", STR_AppName);
            }
        }
Ejemplo n.º 18
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);
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// 创建服务端
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        public static void Server <T>(T entity, int serverPort) where T : TProcessor
        {
            try
            {
                TServerSocket           serverTransport = new TServerSocket(serverPort);
                TBinaryProtocol.Factory factory         = new TBinaryProtocol.Factory();
                //TMultiplexedProcessor processorMulti = new TMultiplexedProcessor();
                //processorMulti.RegisterProcessor("Service", entity);

                TServer server = new TThreadPoolServer(entity, serverTransport, new TTransportFactory(), factory);

                Console.WriteLine(string.Format("服务端正在监听{0}端口", serverPort));
                server.Serve();
            }
            catch (TTransportException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public SpanProcessor(BlockingCollection <Span> spanQueue, IClientProvider clientProvider, int maxBatchSize)
        {
            if (spanQueue == null)
            {
                throw new ArgumentNullException("spanQueue is null");
            }

            if (clientProvider == null)
            {
                throw new ArgumentNullException("clientProvider is null");
            }

            this.spanQueue           = spanQueue;
            this.clientProvider      = clientProvider;
            this.maxBatchSize        = maxBatchSize;
            logEntries               = new List <LogEntry>();
            protocolFactory          = new TBinaryProtocol.Factory();
            spanProcessorTaskFactory = new SpanProcessorTaskFactory();
        }
Ejemplo n.º 21
0
        static async Task RunNotificationServiceAsync()
        {
            var fabric  = new LoggerFactory().AddConsole(LogLevel.Trace);
            var handler = new NotificationHandler();

            ITAsyncProcessor processor       = null;
            TServerTransport serverTransport = null;

            serverTransport = new TServerSocketTransport(9090);

            ITProtocolFactory inputProtocolFactory;
            ITProtocolFactory outputProtocolFactory;

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

            var server = new AsyncBaseServer(processor, serverTransport, inputProtocolFactory, outputProtocolFactory, fabric);
            await server.ServeAsync(new CancellationToken());
        }
Ejemplo n.º 22
0
        static void Main(string[] args)
        {
            try

            {
                //设置服务端口为8080

                TServerSocket serverTransport = new TServerSocket(8800);



                //设置传输协议工厂

                TBinaryProtocol.Factory factory = new TBinaryProtocol.Factory();



                //关联处理器与服务的实现

                TProcessor processor = new UserService.Processor(new User());



                //创建服务端对象

                TServer server = new TThreadPoolServer(processor, serverTransport, new TTransportFactory(), factory);

                Console.WriteLine("服务端正在监听8800端口");
                server.Serve();

                Console.ReadLine();
            }

            catch (TTransportException ex)//捕获异常信息

            {
                //打印异常信息

                Console.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 23
0
        public Task StartAsync(EndPoint endPoint)
        {
            try
            {
                CancellationToken cancellationToken = new CancellationToken();
                var ipEndPoint = endPoint as IPEndPoint;
                TMultiplexedServiceProcessor processor = new TMultiplexedServiceProcessor(_logger, _transportMessageDecoder, _transportMessageEncoder, new ServerHandler(async(contenxt, message) =>
                {
                    var sender = new ThriftServerMessageSender(_transportMessageEncoder, contenxt);
                    await OnReceived(sender, message);
                }, _logger));
                foreach (var entry in _entries)
                {
                    var attr = entry.Type.GetCustomAttribute <BindProcessorAttribute>();

                    if (attr != null)
                    {
                        var asyncProcessor = Activator.CreateInstance(attr.ProcessorType, new object[] { entry.Behavior }) as ITAsyncProcessor;
                        processor.RegisterProcessor(entry.Type.Name, asyncProcessor);
                    }
                }
                var factory1        = new TBinaryProtocol.Factory();
                var factory2        = new TBinaryProtocol.Factory();
                var serverTransport = new TServerSocketTransport(new TcpListener(ipEndPoint));
                var config          = new Configuration();
                config.MaxWorkerThreads = 200;
                config.MinWorkerThreads = 10;
                var server = new TThreadPoolAsyncServer(new TSingletonProcessorFactory(processor), serverTransport, new TFramedTransport.Factory(), new TFramedTransport.Factory(), factory1, factory2, config, _logger);
                server.ServeAsync(cancellationToken);

                if (_logger.IsEnabled(LogLevel.Debug))
                {
                    _logger.LogDebug($"Thrift服务主机启动成功,监听地址:{endPoint}。");
                }
            }
            catch
            {
                _logger.LogError($"Thrift服务主机启动失败,监听地址:{endPoint}。 ");
            }
            return(Task.CompletedTask);
        }
Ejemplo n.º 24
0
        protected override void ServerRegister(SuperGMSServerConfig server)
        {
            try
            {
                serverTransport = new TServerSocket(server.Port);

                // 传输协议
                TBinaryProtocol.Factory factory = new TBinaryProtocol.Factory();
                TProcessor processor            = new ThriftService.Processor(this);
                ts = new TThreadedServer(processor, serverTransport, new TTransportFactory(), factory);
                ts.Serve();
            }
            catch (TTransportException tex)
            {
                logger.LogError(tex, "ThriftServer.ServerRegister.TTransportException.Error");
                throw tex;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "ThriftServer.ServerRegister.Exception.Error");
                throw ex;
            }
        }
Ejemplo n.º 25
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();
        }
Ejemplo n.º 26
0
        private static async Task RunSelectedConfigurationAsync(Transport transport, Protocol protocol, CancellationToken cancellationToken)
        {
            var fabric  = new LoggerFactory().AddConsole(LogLevel.Trace).AddDebug(LogLevel.Trace);
            var handler = new ThriftService();
            ITAsyncProcessor processor       = null;
            TServerTransport serverTransport = null;

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

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

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

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

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

            ITProtocolFactory inputProtocolFactory;
            ITProtocolFactory outputProtocolFactory;

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

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

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

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

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

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


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

                processor = multiplexedProcessor;
                break;

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

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

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

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

                await server.ServeAsync(cancellationToken);
            }
            catch (Exception ex)
            {
                Logger.LogInformation(ex, ex.Message);
            }
        }
Ejemplo n.º 27
0
 public HttpSamplingManager(string hostPort)
 {
     _hostPort        = hostPort ?? DefaultHostPort;
     _protocolFactory = new TBinaryProtocol.Factory();
 }
Ejemplo n.º 28
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());
            }
        }
Ejemplo n.º 29
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.");
        }
Ejemplo n.º 30
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);
        }