public void initData() { typeKey.Add(10, "M基站"); typeValue.Add("M基站", 10); typeKey.Add(11, "R基站"); typeValue.Add("R基站", 11); typeKey.Add(12, "C基站"); typeValue.Add("C基站", 12); try { trans = new TSocket("localhost", 9090); trans = new TFramedTransport(trans); trans.Open(); TProtocol Protocol = new TBinaryProtocol(trans, true, true); TMultiplexedProtocol multiplex; multiplex = new TMultiplexedProtocol(Protocol, "LogicFunctionService"); client = new LogicFunctionService.Client(multiplex); } catch (Exception ex) { MessageBox.Show("初始化异常:" + ex.Message); return; } loadDataToView(); }
protected virtual I ConnectClient(bool silent = false) { const int TIMEOUT = 15 * 1000; try { // try to connect this server using timeout if (!silent) { Console.Write("Testing for server at {0}:{1} ... ", Server, Port); } using (var test = new TSocket(Server, Port, TIMEOUT)) test.Open(); if (!silent) { Console.WriteLine("OK", Server, Port); } var trans = new TFramedTransport(new TSocket(Server, Port, TIMEOUT)); var proto = new TBinaryProtocol(trans); var mplex = new TMultiplexedProtocol(proto, MultiplexName()); trans.Open(); return(ClientFactory(mplex)); } catch (Exception e) { Console.WriteLine("Machine {0} port {1}: {2}", Server, Port, e.Message); } throw new Exception(string.Format("{0}: Can't reach a server at {1}:{2} ... ", DateTime.UtcNow, Server, Port)); }
private static async Task RunClientAsync(TProtocol protocol, bool multiplex, CancellationToken cancellationToken) { try { try { if (multiplex) { protocol = new TMultiplexedProtocol(protocol, nameof(Calculator)); } var client = new Calculator.Client(protocol); await ExecuteCalculatorClientOperations(client, cancellationToken); } catch (Exception ex) { Logger.LogError(ex.ToString()); } finally { protocol.Transport.Close(); } } catch (TApplicationException x) { Logger.LogError(x.ToString()); } }
/** * 获取手机屏幕分辨率 **/ 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(""); }
static void Main(string[] args) { using (TTransport transport = new TSocket("localhost", 9081)) using (TProtocol protocol = new TBinaryProtocol(transport)) using (var protocolHelloService = new TMultiplexedProtocol(protocol, "helloService")) using (var clientHello = new HelloService.Client(protocolHelloService)) using (var protocolSchoolService = new TMultiplexedProtocol(protocol, "schoolService")) using (var clientSchool = new SchoolService.Client(protocolSchoolService)) { transport.Open(); Console.WriteLine(clientHello.HelloString("hello world")); Console.WriteLine("==========================="); //调用服务端的方法 var result = clientSchool.GetAllBanji(); Console.WriteLine(result.SchoolName); foreach (var item in result.AllBanji) { Console.WriteLine("--" + item.BanjiName); foreach (var student in item.AllStudents) { Console.WriteLine("----" + student.StudentName); } } } Console.ReadKey(); }
private static void Main(string[] args) { //using (TTransport transport = new TSocket("127.0.0.1", 8888)) //using (TProtocol protocol = new TBinaryProtocol(transport)) //using (var clientUser = new UserService.Client(protocol)) //{ // transport.Open(); // User u = clientUser.Get(1); // Console.WriteLine($"{u.Id},{u.Name}"); //} using (TTransport transport = new TSocket("127.0.0.1", 8888)) using (TProtocol protocol = new TBinaryProtocol(transport)) using (var protocolUserService = new TMultiplexedProtocol(protocol, "userService")) using (var clientUser = new UserService.Client(protocolUserService)) using (var protocolCalcService = new TMultiplexedProtocol(protocol, "calcService")) using (var clientCalc = new CalcService.Client(protocolCalcService)) { transport.Open(); User u = clientUser.Get(1); Console.WriteLine($"{u.Id},{u.Name}"); Console.WriteLine(clientCalc.Add(1, 2)); } Console.ReadKey(); }
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(); }
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(""); }
public Extension(string launchKey, string canonicalName, Version version, string vendor, ISet <string> supportedLanguages, string hostname = "localhost", int port = 36888) { transport = new TSocket(hostname, port); transport.Open(); protocol = new TBinaryProtocol(transport); extensionProtocol = new TMultiplexedProtocol(protocol, "Extension"); controllerProtocol = new TMultiplexedProtocol(protocol, "Controller"); pendantProtocol = new TMultiplexedProtocol(protocol, "Pendant"); client = new API.Extension.Client(extensionProtocol); var languages = new THashSet <string>(); foreach (var language in supportedLanguages) { languages.Add(language); } id = client.registerExtension(launchKey, canonicalName, version, vendor, languages); if (id == 0) { throw new Exception("Extension registration failed."); } controllerMap = new Dictionary <long, Controller>(); pendantMap = new Dictionary <long, Pendant>(); }
protected virtual object CreateInstance(Service service, TTransport transport) { ThriftService thriftService = service as ThriftService; if (thriftService == null) { throw new InvalidCastException("无法转换成ThriftService"); } if (transport == null) { throw new ArgumentNullException(nameof(transport)); } if (!transport.IsOpen) { transport.Open(); } TProtocol protocol = new TBinaryProtocol(transport); TMultiplexedProtocol multiplexedProtocol = new TMultiplexedProtocol(protocol, thriftService.Name); object instance = Activator.CreateInstance(thriftService.ServiceType, multiplexedProtocol); IDynamicProxyBuilder proxyBuilder = GlobalSetting.GetService <IDynamicProxyBuilder>(); if (proxyBuilder == null) { return(instance); } Type proxyType = proxyBuilder.CreateProxy(thriftService.ServiceInterfaceType); return(Activator.CreateInstance(proxyType, instance)); }
public ServerConnection() { try { TTransport transport = new TSocketTransport("localhost", 5000); TBinaryProtocol protocol = new TBinaryProtocol(transport); TMultiplexedProtocol multiplexedProtocolConsumer = new TMultiplexedProtocol(protocol, "ConsumerService"); consumerService = new ConsumerService.Client(multiplexedProtocolConsumer); TMultiplexedProtocol multiplexedProtocolContentCreator = new TMultiplexedProtocol(protocol, "ContentCreatorService"); contentCreatorService = new ContentCreatorService.Client(multiplexedProtocolContentCreator); TMultiplexedProtocol multiplexeProtocolAlbum = new TMultiplexedProtocol(protocol, "AlbumService"); albumService = new AlbumService.Client(multiplexeProtocolAlbum); TMultiplexedProtocol multiplexeProtocolTrack = new TMultiplexedProtocol(protocol, "TrackService"); trackService = new TrackService.Client(multiplexeProtocolTrack); TMultiplexedProtocol multiplexedProtocolPlaylist = new TMultiplexedProtocol(protocol, "PlaylistService"); playlistService = new PlaylistService.Client(multiplexedProtocolPlaylist); TMultiplexedProtocol multiplexeProtocolLibrary = new TMultiplexedProtocol(protocol, "LibraryService"); libraryService = new LibraryService.Client(multiplexeProtocolLibrary); } catch (Exception ex) { Console.WriteLine(ex + " in Session class"); } }
public static void TestClient() { TTransport transport = new TFramedTransport(new TSocket("localhost", 9090)); TProtocol protocol = new TBinaryProtocol(transport); TMultiplexedProtocol mp = new TMultiplexedProtocol(protocol, "search_service"); SearchService.Client client = new SearchService.Client(mp); transport.Open(); SearchRequest req = new SearchRequest(); req.FileMask = "*.bat"; req.StartPath = "c:\\"; req.IgnoreErrors = true; var result = client.Search(req); Debug.WriteLine("P10"); client.Delay1(2000); client.Delay2(1000); Task t1 = Task.Factory.StartNew(() => { Debug.WriteLine("T1:begin"); client.Delay1(2000); Debug.WriteLine("T1:end"); }); Task t2 = Task.Factory.StartNew(() => { Debug.WriteLine("T2:begin"); client.Delay2(1000); Debug.WriteLine("T2:end"); }); Debug.WriteLine("P20"); t2.Wait(); Debug.WriteLine("P30"); t1.Wait(); Debug.WriteLine("P40"); }
/** * 点击事件 **/ 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(); } }
/// <summary> /// Initializes this instance. /// </summary> private void Initialize() { this.socket = new TSocket(this.ConnectionSetting.Host, this.ConnectionSetting.Port, this.ConnectionSetting.Timeout * 1000); this.socket.TcpClient.NoDelay = true; this.transport = new TFramedTransport(this.socket); var protocol = new TMultiplexedProtocol(new TBinaryProtocol(this.transport), "ThriftSHandler"); this.client = new ThriftSHandler.Client(protocol); }
//初始化 public bool Init() { lock (this) { try { transport = new TSocket(m_host, m_port, m_timeout); protocol = new TBinaryProtocol(transport); TMultiplexedProtocol mp = new TMultiplexedProtocol(protocol, "SercurityService"); SercurityClient = new SercurityService.Client(mp); TMultiplexedProtocol mp2 = new TMultiplexedProtocol(protocol, "SaleService"); SaleClient = new SaleService.Client(mp2); TMultiplexedProtocol mp3 = new TMultiplexedProtocol(protocol, "DataSyncService"); DataSyncClient = new DataSyncService.Client(mp3); if (transport != null && !transport.IsOpen) { transport.Open(); } return(true); } catch (Exception ex) { if (transport != null) { transport.Dispose(); } if (protocol != null) { protocol.Dispose(); } if (DataSyncClient != null) { DataSyncClient.Dispose(); } if (SaleClient != null) { SaleClient.Dispose(); } if (SercurityClient != null) { SercurityClient.Dispose(); } if (SystemClient != null) { SystemClient.Dispose(); } transport = null; protocol = null; SercurityClient = null; SystemClient = null; SaleClient = null; DataSyncClient = null; _log.Error(ex.Message.ToString()); return(false); } } }
private static async Task RunClientAsync(Tuple <Protocol, TProtocol> protocolTuple, CancellationToken cancellationToken) { try { var protocol = protocolTuple.Item2; var protocolType = protocolTuple.Item1; TBaseClient client = null; try { if (protocolType != Protocol.Multiplexed) { client = new Calculator.Client(protocol); //await ExecuteCalculatorClientOperations(cancellationToken, (Calculator.Client)client); await ExecuteCalculatorClientTest(cancellationToken, (Calculator.Client) client); //Stopwatch sw2 = Stopwatch.StartNew(); //for (int i = 0; i < 10; i++) //{ // await ExecuteCalculatorClientTest(cancellationToken, (Calculator.Client)client); //} //sw2.Stop(); //long ms = sw2.ElapsedMilliseconds; //Logger.LogInformation($"RunClientAsync 10 do:10 ms:{sw2.ElapsedMilliseconds}"); } else { var multiplex = new TMultiplexedProtocol(protocol, nameof(Calculator)); client = new Calculator.Client(multiplex); await ExecuteCalculatorClientOperations(cancellationToken, (Calculator.Client) client); multiplex = new TMultiplexedProtocol(protocol, nameof(SharedService)); client = new SharedService.Client(multiplex); await ExecuteSharedServiceClientOperations(cancellationToken, (SharedService.Client) client); //await ExecuteCalculatorClientOperations(cancellationToken, (Calculator.Client)client); } } catch (Exception ex) { Logger.LogError(ex, $"{client?.ClientId}" + ex); } finally { protocol.Transport.Close(); Logger.LogInformation($"finally"); } } catch (TApplicationException x) { Logger.LogError(x, x.ToString()); } }
static void Main(string[] args) { var section = ConfigurationManager.GetSection("thrift.clients") as ClientSection; Console.WriteLine("{0} {1} {2}", section.Host, section.Port, section.Timeout); foreach (var clientConfig in section.Clients) { Console.WriteLine("{0} {1} {2} {3}", clientConfig.ServiceName, clientConfig.Host, clientConfig.Port, clientConfig.Timeout); } var transport = new TSocket("localhost", 20188); var protocol = new TBinaryProtocol(transport); TMultiplexedProtocol protocol1 = new TMultiplexedProtocol(protocol, typeof(AddressRpc).FullName); var client = new AddressRpc.Client(protocol1); TMultiplexedProtocol protocol2 = new TMultiplexedProtocol(protocol, typeof(SmsSendShortMessageRpc).FullName); var client2 = new SmsSendShortMessageRpc.Client(protocol2); var factory = new ThriftClientFactory <SmsSendShortMessageRpc.Client>(); client2 = factory.Create(); var client3 = factory.Create(); factory.Open(); transport.Open(); var input = string.Empty; do { try { var id = client.GetNewId(); var ent = client.Get(id); var updatedResult = client.Update(ent); Console.WriteLine("AddressRpc id:{0}\n obj:{1}\n update:{2}", id, ent.ToString(), updatedResult); var id2 = client2.GetNewId(); var id3 = client3.GetNewId(); var ent2 = client2.Get(id2.ToString()); var ent3 = client3.Get(id3.ToString()); Console.WriteLine("SmsSendShortMessageRpc id:{0} ent:{1} {2} {3}", id2, ent2, id3, ent3); } catch (Exception ex) { Console.WriteLine(ex); } input = Console.ReadLine(); } while (input.ToLower() != "q"); }
static void Main(string[] args) { //调用服务端的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(); transport.Close(); }
private static void Main(string[] args) { var transport = new TSocket("localhost", 9090, 100); var binaryProtocol = new TBinaryProtocol(transport); var bookServiceProtocol = new TMultiplexedProtocol(binaryProtocol, nameof(BookService)); var userAccountServiceProtocol = new TMultiplexedProtocol(binaryProtocol, nameof(UserAccountService)); var bookServiceClient = new BookService.Client(bookServiceProtocol); var userAccountServiceClient = new UserAccountService.Client(userAccountServiceProtocol); try { transport.Open(); var allBooks = bookServiceClient.GetAllBooks(); // Thrift call var allUserAccounts = userAccountServiceClient.GetAllUserAccounts(); // Thrift call Console.WriteLine("Total number of books: {0}", allBooks.Count); Console.WriteLine("Total number of user accounts: {0}\n", allUserAccounts.Count); if (allBooks.Any()) { Console.Write("Getting the first book: "); var firstBook = bookServiceClient.GetBook(allBooks.First().Id); // Thrift call Console.WriteLine("Id: {0}, {1} by {2}", firstBook.Id, firstBook.Title, firstBook.Author); } if (allUserAccounts.Any()) { Console.Write("Getting the last user account: "); var lastUserAccount = userAccountServiceClient.GetUserAccount(allUserAccounts.Last().Id); // Thrift call Console.WriteLine("Id: {0}, Username: {1}", lastUserAccount.Id, lastUserAccount.Username); } } catch (SocketException e) { Console.WriteLine("Could not connect to the server: {0}.", e.Message); } catch (Exception e) { Console.WriteLine("An error occured: {0}", e.Message); } Console.WriteLine("\nDone. Press any key to continue..."); Console.ReadKey(true); }
private static void Main(string[] args) { using (TTransport transport = new TSocket("localhost", 8800)) using (TProtocol protocol = new TBinaryProtocol(transport)) using (var protocolUserService = new TMultiplexedProtocol(protocol, "UserService")) using (var clientUser = new UserService.Client(protocolUserService)) using (var protocolCalcService = new TMultiplexedProtocol(protocol, "CalcService")) using (var clientCalc = new CalcService.Client(protocolCalcService)) { transport.Open(); User u = clientUser.Get(1); Console.WriteLine($"{u.Id},{u.Name}"); Console.WriteLine(clientCalc.Add(1, 2)); } }
static void Main() { using (var consul = new Consul.ConsulClient(c => { c.Address = new Uri("http://127.0.0.1:8500"); })) { //获取在Consul注册的全部服务 var services = consul.Agent.Services().Result.Response; foreach (var s in services.Values) { Console.WriteLine($"ID={s.ID},Service={s.Service},Addr={s.Address},Port={s.Port}"); } var service = consul.Agent.Services().Result.Response.Values.Where( p => p.Service.Equals("test-server-rpc", StringComparison.OrdinalIgnoreCase)).First(); /* * thrift的使用中一般是一个Server对应一个Processor和一个Transport,如果有多个服务的话,那必须要启动多个Server, * 占用多个端口,这种方式显然不是我们想要的,所以thrift为我们提供了复用端口的方式, * 通过监听一个端口就可以提供多种服务, * 这种方式需要用到两个类:TMultiplexedProcessor和TMultiplexedProtocol。 * */ IPAddress ip = IPAddress.Parse(service.Address); using (TcpClient tcpClient = new System.Net.Sockets.TcpClient()) { tcpClient.Connect(ip, service.Port); using (TTransport transport = new TSocket(tcpClient)) { TTransport frameTransport = new TFramedTransport(transport); TProtocol protocol = new TCompactProtocol(frameTransport); //如果服务端使用TMultiplexedProcessor接收处理,客户端必须用TMultiplexedProtocol并且指定serviceName和服务端的一致 TMultiplexedProtocol multiplexedProtocol = new TMultiplexedProtocol(protocol, service.Service + "$com.msunsoft.service.calculator$2.0"); Client client = new Client(multiplexedProtocol); //transport.Open(); Console.WriteLine(client.add(1, 2)); } } } Console.ReadLine(); }
protected override async Task <IClient> CreateClient(URL url) { //实例化TheTransport //获得transport参数,用于反射实例化 var timeout = url.GetParameter(TIMEOUT_KEY, DEFAULT_TIMEOUT); var config = new TConfiguration(); config.MaxFrameSize = url.GetParameter(MAXFRAMESIZE_KEY, config.MaxFrameSize); config.MaxMessageSize = url.GetParameter(MAXMESSAGESIZE_KEY, config.MaxMessageSize); config.RecursionLimit = url.GetParameter(RECURSIONLIMIT_KEY, config.RecursionLimit); var transport = GetTransport(url); Logger().LogInformation($"Selected client transport: {transport}"); var protocol = MakeProtocol(url, MakeTransport(url, config)); Logger().LogInformation($"Selected client protocol: {GetProtocol(url)}"); var mplex = GetMultiplex(url); Logger().LogInformation("Multiplex " + (mplex ? "yes" : "no")); var proxyKey = url.GetParameter(PROXY_KEY); if (string.IsNullOrEmpty(proxyKey) || !_clientTypes.ContainsKey(proxyKey)) { throw new RpcException($"not find the proxy thrift client {url.ToFullString()}"); } if (mplex) { protocol = new TMultiplexedProtocol(protocol, proxyKey); } //instance ThriftClient var client = (TBaseClient)Activator.CreateInstance(_clientTypes[proxyKey], protocol); await Task.CompletedTask; return(new ThriftClient(client, timeout, url)); }
private static async Task RunClientAsync(Tuple <Protocol, TProtocol> protocolTuple, CancellationToken cancellationToken) { try { var protocol = protocolTuple.Item2; var protocolType = protocolTuple.Item1; TBaseClient client = null; try { if (protocolType != Protocol.Multiplexed) { client = new Calculator.Client(protocol); await ExecuteCalculatorClientOperations(cancellationToken, (Calculator.Client) client); } else { // it uses binary protocol there to create Multiplexed protocols var multiplex = new TMultiplexedProtocol(protocol, nameof(Calculator)); client = new Calculator.Client(multiplex); await ExecuteCalculatorClientOperations(cancellationToken, (Calculator.Client) client); multiplex = new TMultiplexedProtocol(protocol, nameof(SharedService)); client = new SharedService.Client(multiplex); await ExecuteSharedServiceClientOperations(cancellationToken, (SharedService.Client) client); } } catch (Exception ex) { Logger.LogError($"{client?.ClientId} " + ex); } finally { protocol.Transport.Close(); } } catch (TApplicationException x) { Logger.LogError(x.ToString()); } }
public async Task <ITransportClient> CreateClientAsync(EndPoint endPoint) { try { var ipEndPoint = endPoint as IPEndPoint; var transport = new TSocketTransport(ipEndPoint.Address.ToString(), ipEndPoint.Port); var tran = new TFramedTransport(transport); var protocol = new TBinaryProtocol(tran); var mp = new TMultiplexedProtocol(protocol, "thrift.surging"); var messageListener = new MessageListener(); var messageSender = new ThriftMessageClientSender(_transportMessageEncoder, protocol); var result = new TThriftClient(protocol, messageSender, messageListener, new ChannelHandler(_transportMessageDecoder, messageListener, messageSender), _app); await result.OpenTransportAsync(); return(result); } catch { throw; } }
public static void Conectar() { Transporte = new TSocket("localhost", 9090); Transporte.Open(); ProtocoloBinario = new TBinaryProtocol(Transporte); CuentaServiceProtocolo = new TMultiplexedProtocol(ProtocoloBinario, nameof(CuentaService)); ExperienciaEducativaServiceProtocolo = new TMultiplexedProtocol(ProtocoloBinario, nameof(ExperienciaEducativaService)); SalonDeClasesServiceProtocolo = new TMultiplexedProtocol(ProtocoloBinario, nameof(SalonDeClasesService)); ChatServiceProtocolo = new TMultiplexedProtocol(ProtocoloBinario, nameof(ChatService)); PresentacionServiceProtocolo = new TMultiplexedProtocol(ProtocoloBinario, nameof(PresentacionService)); CuentaServiceCliente = new CuentaService.Client(CuentaServiceProtocolo); ExperienciaEducativaServiceCliente = new ExperienciaEducativaService.Client(ExperienciaEducativaServiceProtocolo); SalonDeClasesServiceCliente = new SalonDeClasesService.Client(SalonDeClasesServiceProtocolo); ChatServiceCliente = new ChatService.Client(ChatServiceProtocolo); PresentacionServiceCliente = new PresentacionService.Client(PresentacionServiceProtocolo); EstaConectado = true; }
bool ValidateVersion() { // Do version check with layer0 Version ver = Assembly.GetAssembly(GetType()).GetName().Version; var validationProtocol = new TMultiplexedProtocol(LowLatencyProtocol, ServiceIDs.VALIDATOR.ServiceID()); validator = new ValidatorService.Client(validationProtocol); string valid = validator.ValidateSDKAsync(ver.ToString(), CancellationToken.None).Result; if (valid.StartsWith("err:")) { Logger.Log(new LoggerMessage() { Level = LogLevel.Fatal, MsgSource = "SDK", Message = $"SDK version {ver} != ruyi version: {valid}" }); return(false); } else if (valid.StartsWith("warn:")) { Logger.Log(new LoggerMessage() { Level = LogLevel.Warn, MsgSource = "SDK", Message = $"SDK version {ver} != ruyi version: {valid}", }); } else { Logger.Log(new LoggerMessage() { Level = LogLevel.Info, MsgSource = "SDK", Message = "SDK version validated.", }); } return(true); }
public async Task <ITransportClient> CreateClientAsync(EndPoint endPoint) { var key = endPoint; if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug($"准备为服务端地址:{key}创建客户端。"); } try { return(await _clients.GetOrAdd(key , k => new Lazy <Task <ITransportClient> >(async() => { var ipEndPoint = k as IPEndPoint; var transport = new TSocketTransport(ipEndPoint.Address.ToString(), ipEndPoint.Port); var tran = new TFramedTransport(transport); var protocol = new TBinaryProtocol(tran); var mp = new TMultiplexedProtocol(protocol, "thrift.surging"); var messageListener = new MessageListener(); var messageSender = new ThriftMessageClientSender(_transportMessageEncoder, protocol); var result = new TThriftClient(protocol, messageSender, messageListener, new ChannelHandler(_transportMessageDecoder, messageListener, messageSender, _logger), _logger); await result.OpenTransportAsync(); return result; } )).Value);//返回实例 } catch (Exception ex) { //移除 _clients.TryRemove(key, out var value); var ipEndPoint = endPoint as IPEndPoint; //标记这个地址是失败的请求 if (ipEndPoint != null) { await _healthCheckService.MarkFailure(new IpAddressModel(ipEndPoint.Address.ToString(), ipEndPoint.Port)); } throw; } }
static void Main(string[] args) { int flag = 0; while (true) { for (int i = 0; i < 10; i++) { ThriftRequest request = new ThriftRequest { RequestAddress = "APIName", Data = $"Request {flag++}" }; ThriftResponse response = null; using (TTransport trans = new TSocket(_serverIP, _port)) { trans.Open(); using (TProtocol Protocol = new TBinaryProtocol(trans)) { //多服务 using (TMultiplexedProtocol muprotocol = new TMultiplexedProtocol(Protocol, _serverName)) { using (var client = new ServerService.Client(muprotocol)) { response = client.Invoke(request); } } } } Console.WriteLine($"Server Response: Status {response.Status}, Data {response.Data}, ErrMsg {response.ErrMsg}"); } Console.ReadKey(); } }
private void Run() { try { TTransport trans; trans = new TSocket("localhost", 9090); trans = new TFramedTransport(trans); trans.Open(); TProtocol Protocol = new TBinaryProtocol(trans, true, true); TMultiplexedProtocol multiplex; multiplex = new TMultiplexedProtocol(Protocol, Constants.NAME_BENCHMARKSERVICE); BenchmarkService.Iface bench = new BenchmarkService.Client(multiplex); multiplex = new TMultiplexedProtocol(Protocol, Constants.NAME_AGGR); Aggr.Iface aggr = new Aggr.Client(multiplex); sbyte i; for (i = 1; 10 >= i; ++i) { aggr.addValue(bench.fibonacci(i)); } foreach (int k in aggr.getValues()) { Console.Write(k + " "); Console.WriteLine(""); } } catch (Exception e) { Console.WriteLine(e.Message); } }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var trasport = new TSocket("localhost", 8081); var binaryProtocol = new TBinaryProtocol(trasport); var turismServerProtocol = new TMultiplexedProtocol(binaryProtocol, nameof(ITransportServer.Iface)); var server = new ITransportServer.Client(turismServerProtocol); try { trasport.Open(); Application.Run(new Login(server)); } catch (Exception e) { MessageBox.Show(e.StackTrace); } finally { trasport.Close(); } }