static void Main(string[] args) { var proxy = ClientProxyFactory.Create() .UseCastleDynamicClientProxy() .UseJsonNetSerializer() .UseDefaultChannel($"{IPUtility.GetLocalIntranetIP().MapToIPv4()}:5566") .GetClientProxy(); var mathService = proxy.Create <IMathService>(); var random = new Random(); var req = new SumReq { A = random.Next(100000), B = random.Next(100000) }; var result = mathService.SumAsync(req).GetAwaiter().GetResult(); if (result.Code == 0) { Console.WriteLine("Call Math Service Add {0}+{1}={2}", req.A, req.B, result.Data?.Total); } else { Console.WriteLine("Call Math Service Error,Code={0}", result.Code); } Console.WriteLine("Press any key to exit !"); Console.ReadKey(); }
static void Main(string[] args) { /* default route */ var factory = ClientProxyFactory.Create() .UseCastleDynamicClientProxy() .ConfigureLogging(logger => logger.AddConsole()) .UseMessagePackSerializer() .UseDefaultChannel($"{IPUtility.GetLocalIntranetIP().MapToIPv4()}:5566"); /* service discovery route * var factory = ClientProxyFactory.Create() * .ConfigureLogging(logger =>logger.AddConsole()) * .UseCastleDynamicProxy() * .UseMessagePackSerializer() * .UseConsulDnsServiceDiscovery(); //默认配置 localhost */ var proxy = factory.GetProxyInstance(); var mathService = proxy.Create <IMathService>(); var i = 0; var random = new Random(); while (i++ < 100) { var req = new SumReq { A = random.Next(100000), B = random.Next(100000) }; var result = mathService.SumAsync(req).Result; Console.WriteLine("Call Math Service ,return_code={0}", result.Code); if (result.Code == 0) { Console.WriteLine("Call Math Service Add {0}+{1}={2}", req.A, req.B, result.Data?.Total); } Console.WriteLine("============= count:{0}", i); } Console.WriteLine("Press any key to exit !"); Console.ReadKey(); }
private static void Main(string[] args) { var proxy = ClientProxyFactory.Create() .UseCastleDynamicClientProxy() .UseMessagePackSerializer() .UseDefaultChannel($"{IPUtility.GetLocalIntranetIP().MapToIPv4()}:5566") .GetClientProxy(); var service = proxy.Create <IQuickStartService>(); // 项目中应保证异步到底的调用 var res = service.SayHelloAsync(new SayHelloReq { Name = "Maxi" }).GetAwaiter().GetResult(); Console.WriteLine(res?.Data?.GreetingWords); Console.WriteLine("Press any key to exit !"); Console.ReadKey(); }
static void Main(string[] args) { /* * TcpClientOption option = new TcpClientOption { * Certificate = Path.Combine(AppContext.BaseDirectory, "../../../../../shared/dotnetty.com.pfx"), * CertificatePassword = "******" * }; */ //实例化Client 需要传入使用的协议 //TcpClient<CommandLineMessage> client = new TcpClient<CommandLineMessage>(option,new CommandLineChannelHandlerPipeline()); TcpClient <CommandLineMessage> client = new TcpClient <CommandLineMessage>(new CommandLineChannelHandlerPipeline()); client.OnReceived += Client_OnReceived; client.OnConnected += Client_OnConnected; client.OnIdleState += Client_OnIdleState; client.OnDisconnected += Client_OnDisconnected; client.OnError += Client_OnError; Task.Run(async() => { //连接服务器,可以链接多个哦 var socketContext = await client.ConnectAsync(new IPEndPoint(IPUtility.GetLocalIntranetIP(), 5566)); //发送消息 Console.WriteLine("send msg init"); var initCmd = new CommandLineMessage("init"); await socketContext.SendAsync(initCmd); Console.WriteLine("send msg echo hello"); //发送消息2 var echoCmd = new CommandLineMessage("echo", "hello"); await socketContext.SendAsync(echoCmd); Console.WriteLine("Press any key to exit!"); Console.ReadKey(); //关闭链接 await client.ShutdownGracefullyAsync(2000, 2000); }).Wait(); }
static void Main(string[] args) { /* * TcpClientOption option = new TcpClientOption { * Certificate = Path.Combine(AppContext.BaseDirectory, "../../../../../shared/dotnetty.com.pfx"), * CertificatePassword = "******" * }; */ //实例化Client 需要传入使用的协议 //TcpClient<CommandLineMessage> client = new TcpClient<CommandLineMessage>(option,new CommandLineChannelHandlerPipeline()); TcpClient <MqttMessage> client = new TcpClient <MqttMessage>(new MqttChannelHandlerPipeline(new MqttOptions())); client.OnReceived += Client_OnReceived; client.OnConnected += Client_OnConnected; Task.Run(async() => { //连接服务器,可以链接多个哦 var socketContext = await client.ConnectAsync(new IPEndPoint(IPUtility.GetLocalIntranetIP(), 5566)); //发送消息 var connPack = new ConnectPacket { ClientId = Guid.NewGuid().ToString("N") }; await socketContext.SendAsync(new MqttMessage { Packet = connPack }); Console.WriteLine("Press any key to exit!"); Console.ReadKey(); //关闭链接 await client.ShutdownGracefullyAsync(2000, 2000); }).Wait(); }
public async Task StartAsync(CancellationToken cancellationToken) { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { System.Runtime.GCSettings.LatencyMode = System.Runtime.GCLatencyMode.SustainedLowLatency; } //if (_options.UseLibuv) //{ // var dispatcher = new DispatcherEventLoopGroup(); // _bossGroup = dispatcher; // _workerGroup = new WorkerEventLoopGroup(dispatcher); //} //else { // 主的线程 _bossGroup = new MultithreadEventLoopGroup(1); // 工作线程,默认根据CPU计算 _workerGroup = new MultithreadEventLoopGroup(); } var bootstrap = new ServerBootstrap() .Group(_bossGroup, _workerGroup); //if (_options.UseLibuv) { //bootstrap.Channel<TcpServerChannel>(); } //else { bootstrap.Channel <TcpServerSocketChannel>(); } bootstrap.Option(ChannelOption.SoBacklog, _options.SoBacklog); //NOTE: 是否可以公开更多Netty的参数 if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { bootstrap .Option(ChannelOption.SoReuseport, true) .ChildOption(ChannelOption.SoReuseaddr, true); } X509Certificate2 tlsCertificate = null; if (!string.IsNullOrEmpty(_options.Certificate)) { tlsCertificate = new X509Certificate2(_options.Certificate, _options.CertificatePassword); } _ = bootstrap.Handler(new LoggingHandler("LSTN")) .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel => { var pipeline = channel.Pipeline; if (tlsCertificate != null) { pipeline.AddLast("tls", TlsHandler.Server(tlsCertificate)); } pipeline.AddLast(new LoggingHandler("CONN")); foreach (var kv in _handlerPipeline.BuildPipeline(true)) { pipeline.AddLast(kv.Key, kv.Value); } //业务处理Handler,即解码成功后如何处理消息的类 pipeline.AddLast(new TcpServerChannelHandlerAdapter <TMessage>(_socketService)); })); if (_options.BindType == AddressBindType.Any) { _channel = await bootstrap.BindAsync(_options.Port); } else if (_options.BindType == AddressBindType.InternalAddress) { var localPoint = IPUtility.GetLocalIntranetIP(); if (localPoint == null) { this._logger.LogWarning("there isn't an avaliable internal ip address,the service will be hosted at loopback address."); _channel = await bootstrap.BindAsync(IPAddress.Loopback, _options.Port); } else { //this._logger.LogInformation("TcpServerHost bind at {0}",localPoint); _channel = await bootstrap.BindAsync(localPoint, this._options.Port); } } else if (_options.BindType == AddressBindType.Loopback) { _channel = await bootstrap.BindAsync(IPAddress.Loopback, _options.Port); } else { _channel = await bootstrap.BindAsync(IPAddress.Parse(_options.SpecialAddress), _options.Port); } Console.Write(_options.StartupWords, _channel.LocalAddress); }
/// <summary> /// new /// </summary> /// <param name="port"></param> /// <param name="serviceType"></param> /// <param name="zkConfigPath"></param> /// <param name="zkConfigName"></param> /// <param name="zNode"></param> /// <param name="owner"></param> public ZookeeperRegistry(int port, string serviceType, string zkConfigPath, string zkConfigName, string zNode, string owner) { if (string.IsNullOrEmpty(serviceType)) { throw new ArgumentNullException("serviceType"); } if (string.IsNullOrEmpty(zkConfigPath)) { throw new ArgumentNullException("zkConfigPath"); } if (string.IsNullOrEmpty(zkConfigName)) { throw new ArgumentNullException("zkConfigName"); } if (string.IsNullOrEmpty(zNode)) { throw new ArgumentNullException("zNode"); } this._zk = ZookClientPool.Get(zkConfigPath, "zookeeper", zkConfigName); this.RegisterZNode(new NodeInfo[] { new NodeInfo(string.Concat("/", zNode), null, IDs.OPEN_ACL_UNSAFE, CreateModes.Persistent), new NodeInfo(string.Concat("/", zNode, "/providers"), null, IDs.OPEN_ACL_UNSAFE, CreateModes.Persistent) }); this._sessionNode = new SessionNode(this._zk, string.Concat("/", zNode, "/providers/", Uri.EscapeDataString(string.Format( @"thrift2://{0}:{1}/{2}?anyhost=true&application={3}&dispatcher=message&dubbo=2.5.1& interface={2}&loadbalance=roundrobin&methods={7}&owner={4}&pid={5}&revision=0.0.2-SNAPSHOT& side=provider&threads=100×tamp={6}", IPUtility.GetLocalIntranetIP().ToString(), port.ToString(), zNode, Process.GetCurrentProcess().ProcessName, owner ?? "", Process.GetCurrentProcess().Id.ToString(), Date.ToMillisecondsSinceEpoch(DateTime.UtcNow).ToString(), string.Join(",", Type.GetType(serviceType).GetInterfaces()[0].GetMethods().Select(c => c.Name).ToArray())))), null, IDs.OPEN_ACL_UNSAFE); }
public async Task StartAsync(CancellationToken cancellationToken) { // 主的线程 this._bossGroup = new MultithreadEventLoopGroup(1); // 工作线程,默认根据CPU计算 this._workerGroup = new MultithreadEventLoopGroup(); var bootstrap = new ServerBootstrap() .Group(this._bossGroup, this._workerGroup); if (this._options.UseLibuv) { bootstrap.Channel <TcpServerChannel>(); } else { bootstrap.Channel <TcpServerSocketChannel>(); } bootstrap.Channel <TcpServerSocketChannel>() .Option(ChannelOption.SoBacklog, this._options.SoBacklog); //NOTE: 是否可以公开更多Netty的参数 if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { bootstrap .Option(ChannelOption.SoReuseport, true) .ChildOption(ChannelOption.SoReuseaddr, true); } bootstrap.Handler(new LoggingHandler("LSTN")) .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel => { var pipeline = channel.Pipeline; //TODO:ssl support pipeline.AddLast(new LoggingHandler("CONN")); var meta = this._protocol.GetProtocolMeta(); if (meta != null) { // IdleStateHandler pipeline.AddLast("timeout", new IdleStateHandler(0, 0, meta.HeartbeatInterval / 1000 * 2)); //服务端双倍来处理 //消息前处理 pipeline.AddLast( new LengthFieldBasedFrameDecoder( meta.MaxFrameLength, meta.LengthFieldOffset, meta.LengthFieldLength, meta.LengthAdjustment, meta.InitialBytesToStrip ) ); } else //Simple Protocol For Test { pipeline.AddLast("timeout", new IdleStateHandler(0, 0, 360)); // heartbeat each 6 second pipeline.AddLast("framing-enc", new LengthFieldPrepender(2)); pipeline.AddLast("framing-dec", new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2)); } //收到消息后的解码处理Handler pipeline.AddLast(new ChannelDecodeHandler <TMessage>(this._protocol)); //业务处理Handler,即解码成功后如何处理消息的类 pipeline.AddLast(new TcpServerChannelHandlerAdapter <TMessage>(this._socketService, this._protocol)); })); if (this._options.BindType == AddressBindType.Any) { this._channel = await bootstrap.BindAsync(this._options.Port); } else if (this._options.BindType == AddressBindType.InternalAddress) { var localPoint = IPUtility.GetLocalIntranetIP(); //this._logger.LogInformation("TcpServerHost bind at {0}",localPoint); this._channel = await bootstrap.BindAsync(localPoint, this._options.Port); } else if (this._options.BindType == AddressBindType.Loopback) { this._channel = await bootstrap.BindAsync(IPAddress.Loopback, this._options.Port); } else { this._channel = await bootstrap.BindAsync(IPAddress.Parse(this._options.SpecialAddress), this._options.Port); } Console.Write(this._options.StartupWords, this._channel.LocalAddress); }
/// <summary> /// new /// </summary> /// <param name="serviceType"></param> /// <param name="zkConfigPath"></param> /// <param name="zkConfigName"></param> /// <param name="zNode"></param> /// <param name="callback"></param> public ZoomkeeperDiscovery(string serviceType, string zkConfigPath, string zkConfigName, string zNode, Action <IPEndPoint[]> callback) { if (string.IsNullOrEmpty(serviceType)) { throw new ArgumentNullException("serviceType"); } if (string.IsNullOrEmpty(zkConfigPath)) { throw new ArgumentNullException("zkConfigPath"); } if (string.IsNullOrEmpty(zkConfigName)) { throw new ArgumentNullException("zkConfigName"); } if (string.IsNullOrEmpty(zNode)) { throw new ArgumentNullException("zNode"); } if (callback == null) { throw new ArgumentNullException("callback"); } this._callback = callback; this._zk = ZookClientPool.Get(zkConfigPath, "zookeeper", zkConfigName); this.RegisterZNode(new NodeInfo[] { new NodeInfo(string.Concat("/", zNode), null, IDs.OPEN_ACL_UNSAFE, CreateModes.Persistent), new NodeInfo(string.Concat("/", zNode, "/consumers"), null, IDs.OPEN_ACL_UNSAFE, CreateModes.Persistent) }); this._sessionNode = new SessionNode(this._zk, string.Concat("/", zNode, "/consumers/", Uri.EscapeDataString(string.Format( @"consumer://{0}/{1}?application={2}&category=consumers&check=false&dubbo=2.5.1& interface={1}&methods={6}&owner={3}&pid={4}&revision=0.0.2-SNAPSHOT& side=consumer×tamp={5}", IPUtility.GetLocalIntranetIP().ToString(), zNode, Process.GetCurrentProcess().ProcessName, string.Empty, Process.GetCurrentProcess().Id.ToString(), Date.ToMillisecondsSinceEpoch(DateTime.UtcNow).ToString(), string.Join(",", Type.GetType(serviceType).GetInterfaces()[0].GetMethods().Select(c => c.Name).ToArray())))), null, IDs.OPEN_ACL_UNSAFE); this._watcher = new ChildrenWatcher(this._zk, string.Concat("/", zNode, "/providers"), arrNodes => { this._callback(arrNodes.Select(c => { var objUri = new Uri(Uri.UnescapeDataString(c)); return(new IPEndPoint(IPAddress.Parse(objUri.Host), objUri.Port)); }).ToArray()); //lock (this._lockObj) //{ // var arrExists = this._thrift.GetAllRegisteredEndPoint().Select(c => c.Key).Distinct().ToArray(); // var arrCurr = arrNodes.Select(node => // { // var strUrl = Uri.UnescapeDataString(node); // strUrl = strUrl.Substring(strUrl.IndexOf(":") + 3); // return strUrl.Substring(0, strUrl.IndexOf("/")); // }).ToArray(); // var set = new HashSet<string>(arrExists); // set.ExceptWith(arrCurr); // if (set.Count > 0) // { // foreach (var child in set) // this._thrift.UnRegisterEndPoint(child); // } // set = new HashSet<string>(arrCurr); // set.ExceptWith(arrExists); // if (set.Count > 0) // { // foreach (var child in set) // { // var i = child.IndexOf(":"); // var endpoint = new IPEndPoint(IPAddress.Parse(child.Substring(0, i)), int.Parse(child.Substring(i + 1))); // this._thrift.TryRegisterEndPoint(child, new EndPoint[] { endpoint }); // } // } //} }); }