private static async Task RunSelectedConfigurationAsync(Transport transport, Buffering buffering, Protocol protocol, bool multiplex, CancellationToken cancellationToken) { TServerTransport serverTransport = transport switch { Transport.Tcp => new TServerSocketTransport(9090, Configuration), Transport.NamedPipe => new TNamedPipeServerTransport(".test", Configuration, NamedPipeClientFlags.None), Transport.TcpTls => new TTlsServerSocketTransport(9090, Configuration, GetCertificate(), ClientCertValidator, LocalCertificateSelectionCallback), _ => throw new ArgumentException("unsupported value $transport", nameof(transport)), }; TTransportFactory transportFactory = buffering switch { Buffering.Buffered => new TBufferedTransport.Factory(), Buffering.Framed => new TFramedTransport.Factory(), // layered transport(s) are optional Buffering.None => null, _ => throw new ArgumentException("unsupported value $buffering", nameof(buffering)), }; TProtocolFactory protocolFactory = protocol switch { Protocol.Binary => new TBinaryProtocol.Factory(), Protocol.Compact => new TCompactProtocol.Factory(), Protocol.Json => new TJsonProtocol.Factory(), _ => throw new ArgumentException("unsupported value $protocol", nameof(protocol)), }; var handler = new CalculatorAsyncHandler(); ITAsyncProcessor processor = new Calculator.AsyncProcessor(handler); if (multiplex) { var multiplexedProcessor = new TMultiplexedProcessor(); multiplexedProcessor.RegisterProcessor(nameof(Calculator), processor); processor = multiplexedProcessor; } try { Logger.LogInformation( "TSimpleAsyncServer with \n{transport} transport\n{buffering} buffering\nmultiplex = {multiplex}\n{protocol} protocol", transport, buffering, multiplex ? "yes" : "no", protocol ); var server = new TSimpleAsyncServer( itProcessorFactory: new TSingletonProcessorFactory(processor), serverTransport: serverTransport, inputTransportFactory: transportFactory, outputTransportFactory: transportFactory, inputProtocolFactory: protocolFactory, outputProtocolFactory: protocolFactory, logger: LoggingHelper.CreateLogger <TSimpleAsyncServer>()); Logger.LogInformation("Starting the server..."); await server.ServeAsync(cancellationToken); } catch (Exception x) { Logger.LogInformation("{x}", x); } }
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); } }
public TransportWindow(ClientController clientController, int port) { InitializeComponent(); StartPosition = FormStartPosition.CenterScreen; ridesView.ReadOnly = true; bookingsView.ReadOnly = true; bookingsView.Columns.Cast <DataGridViewColumn>().ToList().ForEach(f => f.SortMode = DataGridViewColumnSortMode.NotSortable); _clientController = clientController; _clientController.UpdateEvent += _clientController_UpdateEvent; NotifyOnEvent(); var clientProcessor = new ITransportObserver.Processor(_clientController); var processor = new TMultiplexedProcessor(); processor.RegisterProcessor(nameof(ITransportServer.Iface), clientProcessor); var trasport = new TServerSocket(port); _server = new TThreadPoolServer(processor, trasport); FormClosed += (a, b) => { _clientController.Logout(); _clientController.UpdateEvent -= _clientController_UpdateEvent; _server.Stop(); }; _updates = Task.Run(() => { _server.Serve(); }); }
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); } }
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); } }
private static void Main(string[] args) { var bookServiceHandler = new BookServiceHandler(); var userAccountServiceHandler = new UserAccountServiceHandler(); var bookServiceProcessor = new BookService.Processor(bookServiceHandler); var userAccountProcessor = new UserAccountService.Processor(userAccountServiceHandler); var processor = new TMultiplexedProcessor(); processor.RegisterProcessor(nameof(BookService), bookServiceProcessor); processor.RegisterProcessor(nameof(UserAccountService), userAccountProcessor); TServerTransport transport = new TServerSocket(9090); TServer server = new TThreadPoolServer(processor, transport); // TThreadPoolServer accepts multiple clients Console.WriteLine("Starting the server..."); // Start server on a different background thread so the console continues to be responsive var serverThread = new Thread(() => server.Serve()) { IsBackground = true }; serverThread.Start(); Console.WriteLine("Done. Press any key to stop the server..."); Console.ReadKey(true); server.Stop(); }
public void ThrifTestMethod1() { //服务端:开始Thrift rpc服务 new Thread(() => { var processor1 = new HelloThrift.Processor(new HelloThriftHandler()); TMultiplexedProcessor processor = new TMultiplexedProcessor(); processor.RegisterProcessor("HelloThriftHandler", processor1); var serverTransport = new TServerSocket(9090); var server1 = new TThreadedServer(processor, serverTransport); Console.WriteLine("向客户端输出服务开启"); server1.Serve(); }).Start(); //客户端:调用服务端的HelloThrift的HelloWorld方法 TTransport transport = new TSocket("localhost", 9090); TProtocol protocol = new TBinaryProtocol(transport); TMultiplexedProtocol mp1 = new TMultiplexedProtocol(protocol, "HelloThriftHandler"); HelloThrift.Client client = new HelloThrift.Client(mp1); transport.Open(); client.HelloWorld(); client.adding(2, 3); Console.WriteLine(client.GetData(1)); transport.Close(); }
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(); } }
static void Main(string[] args) { //开始Thrift rpc服务 new Thread(() => { var processor1 = new HelloThrift.Processor(new HelloThriftHandler()); TMultiplexedProcessor processor = new TMultiplexedProcessor(); processor.RegisterProcessor("HelloThriftHandler", processor1); var serverTransport = new TServerSocket(9090); var server1 = new TThreadedServer(processor, serverTransport); Console.WriteLine("向客户端输出服务开启"); server1.Serve(); }).Start(); }
public CallbackService(Salon handlerSalon, Salon handlerChat, Salon handlerPresentacion) { ProcessorSalon = new SalonDeClasesCallback.Processor(handlerSalon); ProcessorChat = new ChatCallback.Processor(handlerChat); ProcessorPresentacion = new PresentacionCallback.Processor(handlerPresentacion); Processor = new TMultiplexedProcessor(); Processor.RegisterProcessor(nameof(SalonDeClasesCallback), ProcessorSalon); Processor.RegisterProcessor(nameof(ChatCallback), ProcessorChat); Processor.RegisterProcessor(nameof(PresentacionCallback), ProcessorPresentacion); Transporte = new TServerSocket(9091); Servidor = new TThreadPoolServer(Processor, Transporte); //servidor.Serve(); }
public static void StartServer() { SearchServiceHandler handler = new SearchServiceHandler(); SearchService.Processor processor = new SearchService.Processor(handler); TMultiplexedProcessor multiProcessor = new TMultiplexedProcessor(); multiProcessor.RegisterProcessor("search_service", processor); TServerTransport serverTransport = new TServerSocket(9090); var a = new TFramedTransport.Factory(); TServer server = new TThreadPoolServer(multiProcessor, serverTransport, new TFramedTransport.Factory(), new TBinaryProtocol.Factory()); serverTask = Task.Factory.StartNew(server.Serve); }
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(); }
static void Main(string[] args) { try { var section = ConfigurationManager.GetSection("thrift.hosts") as HostSetion; foreach (var host in section.Hosts) { Console.WriteLine("{0} {1} {2} {3} {4}", host.Name, host.Port, host.MinThreadPoolSize, host.MaxThreadPoolSize, host.Services.Count); foreach (var service in host.Services) { Console.WriteLine("{0} {1}", service.Contract, service.Handler); } } ThriftServer serverHost = new ThriftServer(); serverHost.Start(); TMultiplexedProcessor multiplexedProcessor = new TMultiplexedProcessor(); multiplexedProcessor.RegisterProcessor(typeof(AddressRpc).FullName, new AddressRpc.Processor(new AddressRpcImpl())); multiplexedProcessor.RegisterProcessor(typeof(SmsSendShortMessageRpc).FullName, new SmsSendShortMessageRpc.Processor(new SmsSendShortMessageRpcImpl())); TServerTransport transport = new TServerSocket(6011); TPrototypeProcessorFactory <AddressRpc.Processor, AddressRpcImpl> factory = new TPrototypeProcessorFactory <AddressRpc.Processor, AddressRpcImpl>(); TProcessor processor = factory.GetProcessor(null); TSimpleServer server = new TSimpleServer(multiplexedProcessor, transport, info => { Console.WriteLine(info); }); Console.WriteLine("Begin service..."); server.Serve(); } catch (Exception ex) { Console.WriteLine(ex); } Console.ReadLine(); }
private static void Main(string[] args) { //TServerTransport transport = new TServerSocket(8800); //var processor = new UserService.Processor(new UserServiceImpl()); //TServer server = new TThreadPoolServer(processor, transport); //server.Serve(); //Console.ReadKey(); TServerTransport transport = new TServerSocket(8800); var processorUserService = new UserService.Processor(new UserServiceImpl()); var processorCalcService = new CalcService.Processor(new CalcServiceImpl()); var processorMulti = new TMultiplexedProcessor(); processorMulti.RegisterProcessor("UserService", processorUserService); processorMulti.RegisterProcessor("CalcService", processorCalcService); TServer server = new TThreadPoolServer(processorMulti, transport); server.Serve(); Console.ReadKey(); }
private static void Main(string[] args) { //TServerTransport transport = new TServerSocket(8888); //var processor = new ThriftTest1.Contract.UserService.Processor(new //UserServiceImpl()); //TServer server = new TThreadPoolServer(processor, transport); //server.Serve(); TServerTransport transport = new TServerSocket(8888); var processorUserService = new ThriftTest1.Contract.UserService.Processor(new UserServiceImpl()); var processorCalcService = new ThriftTest1.Contract.CalcService.Processor(new CalcServiceImpl()); var processorMulti = new TMultiplexedProcessor(); processorMulti.RegisterProcessor("userService", processorUserService); processorMulti.RegisterProcessor("calcService", processorCalcService); TServer server = new TThreadPoolServer(processorMulti, transport); server.Serve(); Console.WriteLine("Hello World!"); }
public static void Run(int port, NodeService.Iface iface) { ScreenImpl client = new ScreenImpl(); ScreenService.Processor processor = new global::ScreenService.Processor(client); NodeService.Processor nodeProcessor = new global::NodeService.Processor(iface); TMultiplexedProcessor pro = new TMultiplexedProcessor(); pro.RegisterProcessor("ScreenService", processor); pro.RegisterProcessor("NodeService", nodeProcessor); TServerTransport transport = new TServerSocket(port); TServer server = new TThreadPoolServer(pro, transport); try { server.Serve(); } catch (Exception e) { } }
protected virtual void StartService(IGrouping <int, ThriftService> group) { TMultiplexedProcessor multiplexedProcessor = new TMultiplexedProcessor(); IServiceActivator serviceActivator = GlobalSetting.Container.GetService <IServiceActivator>(); if (serviceActivator == null) { throw new NullReferenceException("未设置IServiceActivator接口"); } foreach (ThriftService service in group) { object instance = serviceActivator.Create(service.ServiceType); if (instance == null) { throw new NullReferenceException($"无法创建服务{service.ServiceType.FullName}"); } Type processorType = ThriftServiceHelper.GetProcessorType(service.ServiceType); if (processorType == null) { throw new NullReferenceException($"无法找到服务{service.ServiceType.FullName}对应的Processor类"); } TProcessor processor = ThriftServiceHelper.CreateProcessor(processorType, instance); if (processor == null) { throw new NullReferenceException($"无法创建Processor{processorType.FullName}"); } multiplexedProcessor.RegisterProcessor(service.Name, processor); } TServerTransport serverTransport = new TServerSocket(group.Key); serverTransport.Listen(); TServer server = new TThreadPoolServer(multiplexedProcessor, serverTransport); _servers.Add(server); Task.Run(() => server.Serve()); }
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); } }
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()); } }
private static void StartServerListener() { ////------------TSimpleServer —— 单线程服务器端使用标准的阻塞式 I/O //new TSimpleServer( // new BasicDataService.Processor(new BasicDataServiceImp()), // new TServerSocket(10091, 0, false)) // .Serve(); { ////-------------TThreadPoolServer —— 多线程服务器端使用标准的阻塞式 I/O ////-------------线程池服务模型,使用标准的阻塞式IO,预先创建一组线程处理请求。 //TServerTransport scoket = new TServerSocket(10091); ////-------------TNamedPipeServerTransport scoket2 = new TNamedPipeServerTransport(); ////TTLSServerSocket scoket3 = new TTLSServerSocket(10091,new X509Certificate2()); //SuperServiceForServer.Processor processor = new SuperServiceForServer.Processor(new SuperServiceForServerImp()); //TThreadPoolServer server = new TThreadPoolServer(processor, scoket); //server.Serve(); } //注册信息记录器 //ServiceLocator.Instance.RegisterInstance<IInfoRecord>(new DebugRecord()); { //对应客户端一 性能好方法 _processor = new TMultiplexedProcessor(); _transport = new TServerSocket(_port); _processor.RegisterProcessor ( _serverName, new ServerService.Processor ( new MainServerImpl() ) ); _server = new TThreadPoolServer ( _processor, _transport ); _server.Serve(); ////对应客户端二 ////-------------------TThreadPoolServer —— 多线程服务器端使用标准的阻塞式 I/O--------多服务注册 ////-------------------线程池服务模型,使用标准的阻塞式IO,预先创建一组线程处理请求。 //TProtocolFactory ProtocolFactory = new TBinaryProtocol.Factory(true, true); //TTransportFactory TransportFactory = new TFramedTransport.Factory(); //TServerTransport scoket1 = new TServerSocket(10091, 0, false); //TMultiplexedProcessor multiplex = new TMultiplexedProcessor(); //multiplex.RegisterProcessor("1", new BasicDataService.Processor(new BasicDataServiceImp())); //multiplex.RegisterProcessor("2", new BasicDataService.Processor(new BasicDataServiceImp())); //TThreadPoolServer server1 = new TThreadPoolServer(multiplex, scoket1, TransportFactory, ProtocolFactory); //server1.Serve(); } { //////-------------TThreadedServer - 多线程服务模型,使用阻塞式IO,每个请求创建一个线程。 //TServerTransport scoket = new TServerSocket(10091); ////-------------TNamedPipeServerTransport scoket2 = new TNamedPipeServerTransport(); ////-------------TTLSServerSocket scoket3 = new TTLSServerSocket(10091,new X509Certificate2()); //BasicDataService.Processor processor = new BasicDataService.Processor(new BasicDataServiceImp()); //TThreadedServer server = new TThreadedServer(processor, scoket); //server.Serve(); } }
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()); } }
private async Task RunSelectedConfigurationAsync(Transport transport, Buffering buffering, Protocol protocol, bool multiplex, CancellationToken cancellationToken) { var port = _thriftServerOption.CurrentValue.Port; var configuration = _thriftServerOption.CurrentValue.Configuration; TServerTransport serverTransport = transport switch { Transport.Tcp => new TServerSocketTransport(port, configuration), Transport.NamedPipe => new TNamedPipeServerTransport(".test", configuration),//, NamedPipeClientFlags.None), Transport.TcpTls => new TTlsServerSocketTransport(9090, configuration, GetCertificate(), ClientCertValidator, LocalCertificateSelectionCallback), _ => throw new ArgumentException("unsupported value $transport", nameof(transport)), }; TTransportFactory transportFactory = buffering switch { Buffering.Buffered => new TBufferedTransport.Factory(), Buffering.Framed => new TFramedTransport.Factory(), // layered transport(s) are optional Buffering.None => null, _ => throw new ArgumentException("unsupported value $buffering", nameof(buffering)), }; TProtocolFactory protocolFactory = protocol switch { Protocol.Binary => new TBinaryProtocol.Factory(), Protocol.Compact => new TCompactProtocol.Factory(), Protocol.Json => new TJsonProtocol.Factory(), Protocol.BinaryHeader => new TBinaryHeaderServerProtocol.Factory(), Protocol.CompactHeader => new TCompactHeaderServerProtocol.Factory(), Protocol.JsonHeader => new TJsonHeaderServerProtocol.Factory(), _ => throw new ArgumentException("unsupported value $protocol", nameof(protocol)), }; //var handler = new CalculatorAsyncHandler(); //ITAsyncProcessor processor = new Calculator.AsyncProcessor(handler); ITAsyncProcessor processor = _asyncProcessorList.FirstOrDefault(); if (multiplex) { var multiplexedProcessor = new TMultiplexedProcessor(); foreach (var item in _asyncProcessorList) { multiplexedProcessor.RegisterProcessor(item.GetType().FullName, item); } processor = multiplexedProcessor; } try { _logger.LogInformation( string.Format( "TSimpleAsyncServer with \n{0} transport\n{1} buffering\nmultiplex = {2}\n{3} protocol", transport, buffering, multiplex ? "yes" : "no", protocol )); _server = new TSimpleAsyncServer( itProcessorFactory: new TSingletonProcessorFactory(processor), serverTransport: serverTransport, inputTransportFactory: transportFactory, outputTransportFactory: transportFactory, inputProtocolFactory: protocolFactory, outputProtocolFactory: protocolFactory, logger: _loggerFactory.CreateLogger <TSimpleAsyncServer>()); //var threadConfig = new TThreadPoolAsyncServer.Configuration(); //var server = new TThreadPoolAsyncServer( // processorFactory: new TSingletonProcessorFactory(processor), // serverTransport: serverTransport, // inputTransportFactory: transportFactory, // outputTransportFactory: transportFactory, // inputProtocolFactory: protocolFactory, // outputProtocolFactory: protocolFactory, // threadConfig: threadConfig, // logger: loggerFactory.CreateLogger<TThreadPoolAsyncServer>()); _logger.LogInformation("Starting the server..."); await _server.ServeAsync(cancellationToken); } catch (Exception x) { _logger.LogInformation(x.ToString()); } }
public static void StartMult() { var _configPath = ConfigurationManager.AppSettings["ThriftServerConfigPath"]; Config.ThriftConfigSection config = null; if (string.IsNullOrEmpty(_configPath)) { config = ConfigurationManager.GetSection("thriftServer") as Config.ThriftConfigSection; } else { config = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap { ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _configPath) }, ConfigurationUserLevel.None).GetSection("thriftServer") as Config.ThriftConfigSection; } if (config == null || config.Services == null) { throw new Exception("thrift服务配置不存在"); } foreach (Service service in config.Services) { new System.Threading.Thread(() => { try { TMultiplexedProcessor multiplexedProcessor = new TMultiplexedProcessor(); Type[] thriftTypes = Assembly.LoadFrom(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, service.ThriftAssembly)).GetTypes(); Type[] thriftImplTypes = Assembly.LoadFrom(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, service.ThriftImplAssembly)).GetTypes(); foreach (var t in thriftTypes) { if (!t.Name.Equals("Iface")) { continue; } string processorFullName = t.FullName.Replace("+Iface", "+Processor"); Type processorType = thriftTypes.FirstOrDefault(c => c.FullName.Equals(processorFullName)); object handle = null; foreach (Type t2 in thriftImplTypes) { if (t2.GetInterfaces().Contains(t)) { handle = TransparentProxy.Create(t2); break; } } var processor = (Thrift.TProcessor)processorType.GetConstructor(new Type[] { t }).Invoke(new object[] { handle }); multiplexedProcessor.RegisterProcessor(t.ReflectedType.Name, processor); } if (service.Port > 0) { if (!PortHelper.PortIsAvailable(service.Port)) { throw new Exception("端口冲突"); } } else { service.Port = PortHelper.GetFirstAvailablePort(); if (service.Port <= 0) { throw new Exception("无端口可用"); } } TServerTransport serverTransport = new TServerSocket(service.Port, service.ClientTimeout); TServer server = new TThreadPoolServer(new BaseProcessor(multiplexedProcessor, service), serverTransport, new TTransportFactory(), new TTransportFactory(), new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(), service.MinThreadPoolThreads, service.MaxThreadPoolThreads, (x) => { ThriftLog.Info("log:" + x); }); RegeditConfig regiditConfig = null; if (service.ZookeeperConfig != null && service.ZookeeperConfig.Host != "") { regiditConfig = ConfigCenter.RegeditServer(service); //zookeeper 注册服务 } ThriftLog.Info($"{service.Name} {service.Port} Starting the TThreadPoolServer..."); _services.Add(server, regiditConfig); server.Serve(); } catch (Exception ex) { ThriftLog.Error(ex.Message + ex.StackTrace); } }).Start(); } }