DotNetty客户端断线重连_第1页
DotNetty客户端断线重连_第2页
DotNetty客户端断线重连_第3页
DotNetty客户端断线重连_第4页
全文预览已结束

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

DotNetty客户端断线重连1、代码如下:usingSystem;usingSystem.Collections.Generic;usingDotNetty.Buffers;usingDotNetty.Transport.Bootstrapping;usingDotNetty.Transport.Channels;usingDotNetty.Transport.Channels.Sockets;usingSystem.Linq;usingSystem.Net;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.IO;usingSystem.Threading;usingTest.Model;usingDotNetty.Handlers.Timeout;usingDotNetty.Handlers.Logging;///zuochao_2013/article/details/72872315namespaceTest{publicclassExliveNettyClient{MultithreadEventLoopGroupgroup;Bootstrapbootstrap;ExliveClientHandlerhandler;publicExliveNettyClient(){group=newMultithreadEventLoopGroup();bootstrap=newBootstrap();handler=newExliveClientHandler(this);bootstrap.Group(group).Channel<TcpSocketChannel>().Option(ChannelOption.TcpNodelay,true).Option(ChannelOption.ConnectTimeout,TimeSpan.FromSeconds(3)).Handler(newActionChannelInitializer<ISocketChannel>(c=>{varpipeline=c.Pipeline;//pipeline.AddLast("timeout",newIdleStateHandler(TimeSpan.FromSeconds(5),TimeSpan.FromSeconds(5),TimeSpan.FromSeconds(5)));pipeline.AddLast(handler);}));bootstrap.RemoteAddress(newIPEndPoint(IPAddress.Parse(AppConfig.ServerIP),AppConfig.ServerPort));RunClientAsync().Wait();}publicasyncTaskConnectToServer(){try{IChannelclientChannel=null;try{clientChannel=awaitbootstrap.ConnectAsync();}catch(Exceptionex){System.Threading.Thread.Sleep(5000);awaitConnectToServer();}}}finally{Console.ReadLine();awaitgroup.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100),TimeSpan.FromSeconds(1));}}privateasyncTaskRunClientAsync(){awaitConnectToServer();}}classExliveClientHandler:ChannelHandlerAdapter,IExliveNetInterface{privateinttotal=0;///<summary>///通道///</summary>privateIChannelHandlerContextcontext;///<summary>///消息处理///</summary>privateMessageProcessmp;///<summary>///客户端///</summary>privateExliveNettyClientclient;///<summary>////w592376568/article/details/79898062///报错:isnota@Sharablehandler///要么就是IsSharable设为true,要么就是每次都new⼀个新的handler的实例///</summary>publicoverrideboolIsSharable=>true;publicExliveClientHandler(ExliveNettyClientclient){this.client=client;mp=newMessageProcess(this);}publicoverridevoidHandlerAdded(IChannelHandlerContextcontext){this.context=context;base.HandlerAdded(context);}publicoverridevoidChannelRegistered(IChannelHandlerContextcontext){base.ChannelRegistered(context);}publicoverridevoidChannelUnregistered(IChannelHandlerContextcontext){}publicoverridevoidChannelActive(IChannelHandlerContextcontext){total=0;mp.SendData(ExliveCmd.LOGIN);base.ChannelActive(context);}publicoverridevoidChannelInactive(IChannelHandlerContextcontext){Reconnect(context);base.ChannelInactive(context);}publicoverridevoidChannelRead(IChannelHandlerContextcontext,objectmessage){if(messageisIByteBufferbuffer){stringdata=buffer.ToString(System.Text.Encoding.GetEncoding("gb2312"));mp.AfterReceiveData(data);stringrecieveText="recieve:"+context.Channel.RemoteAddress.ToString()+"->"+context.Channel.LocalAddress.ToString()+"\r\n"+(string.IsNullOrEmpty(data)?"":data.Trim(newchar[]{'\r','\n'}));//Console.WriteLine(recieveText);Log.WriteLog(recieveText);}}publicoverridevoidChannelReadComplete(IChannelHandlerContextcontext)=>context.Flush();publicoverridevoidHandlerRemoved(IChannelHandlerContextcontext){Reconnect(context);Console.WriteLine($"服务端{context}下线.");base.HandlerRemoved(context);}publicoverridevoidExceptionCaught(IChannelHandlerContextcontext,Exceptionexception){Reconnect(context);base.ExceptionCaught(context,exception);}publicoverridevoidUserEventTriggered(IChannelHandlerContextcontext,objectevt){if(evtisIdleStateEvent){vareventState=evtasIdleStateEvent;if(eventState!=null){switch(eventState.State){caseIdleState.ReaderIdle:break;caseIdleState.WriterIdle://长时间未写⼊数据//则发送⼼跳数据//context.WriteAndFlushAsync();mp.SendData(ExliveCmd.HEART);break;caseIdleState.AllIdle:break;}}}}publicvoidSendPackage(stringdata){byte[]messageBytes=System.Text.Encoding.GetEncoding("gb2312").GetBytes(data);IByteBufferinitialMessage=Unpooled.Buffer(messageBytes.Length);initialMessage.WriteBytes(messageBytes);if(context!=null)context.WriteAndFlushAsync(initialMessage);}publicvoidSendPackage(objectobj){varsendMessage=Json.ToCamelCaseJson(obj);SendPackage(sendMessage);}publicvoidReconnect(IChannelHandlerContextcontext){Interlocked.Increment(reftotal);if(total==1){newAction(async()=>{awaitthis.client.ConnectToServer();}).BeginInvoke(null,null);}}}}2、事件顺序Added->Registered->Active,如果连接成功会执⾏到Active,未成功会在ConnectToServer中

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论