[原]基于netty的心跳检测
- - 一切没有被记录的,终将被遗忘这两天由于要给android系统的设备写一个心跳功能,所以在这里写一个基于netty的心跳检测功能. 1.客户端网络空闲5秒没有进行写操作是,进行发送一次ping心跳给服务端;. 2.客户端如果在下一个发送ping心跳周期来临时,还没有收到服务端pong的心跳应答,则失败心跳计数器加1;. 3.每当客户端收到服务端的pong心跳应答后,失败心跳计数器清零;.
arg0.pipeline().addLast("ping", new IdleStateHandler(25, 15, 10,TimeUnit.SECONDS));
/** * 一段时间未进行读写操作 回调 */ @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { // TODO Auto-generated method stub super.userEventTriggered(ctx, evt); if (evt instanceof IdleStateEvent) { IdleStateEvent event = (IdleStateEvent) evt; if (event.state().equals(IdleState.READER_IDLE)) { //未进行读操作 System.out.println("READER_IDLE"); // 超时关闭channel ctx.close(); } else if (event.state().equals(IdleState.WRITER_IDLE)) { } else if (event.state().equals(IdleState.ALL_IDLE)) { //未进行读写 System.out.println("ALL_IDLE"); // 发送心跳消息 MsgHandleService.getInstance().sendMsgUtil.sendHeartMessage(ctx); } } }
bootstrap.connect(new InetSocketAddress( serverIP, port));
import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.util.Log; import com.ld.qmwj.Config; import com.ld.qmwj.MyApplication; import java.net.InetSocketAddress; import java.nio.charset.Charset; import java.util.concurrent.TimeUnit; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.DelimiterBasedFrameDecoder; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; /** * Created by zsg on 2015/11/21. */ public class MyClient implements Config { private static Bootstrap bootstrap; private static ChannelFutureListener channelFutureListener = null; public MyClient() { } // 初始化客户端 public static void initClient() { NioEventLoopGroup group = new NioEventLoopGroup(); // Client服务启动器 3.x的ClientBootstrap // 改为Bootstrap,且构造函数变化很大,这里用无参构造。 bootstrap = new Bootstrap(); // 指定EventLoopGroup bootstrap.group(group); // 指定channel类型 bootstrap.channel(NioSocketChannel.class); // 指定Handler bootstrap.handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { // 创建分隔符缓冲对象 ByteBuf delimiter = Unpooled.copiedBuffer("#" .getBytes()); // 当达到最大长度仍没找到分隔符 就抛出异常 ch.pipeline().addLast( new DelimiterBasedFrameDecoder(10000, true, false, delimiter)); // 将消息转化成字符串对象 下面的到的消息就不用转化了 //解码 ch.pipeline().addLast(new StringEncoder(Charset.forName("UTF-8"))); ch.pipeline().addLast(new StringDecoder(Charset.forName("GBK"))); ch.pipeline().addLast(new MyClientHandler()); } }); //设置TCP协议的属性 bootstrap.option(ChannelOption.SO_KEEPALIVE, true); bootstrap.option(ChannelOption.TCP_NODELAY, true); bootstrap.option(ChannelOption.SO_TIMEOUT, 5000); channelFutureListener = new ChannelFutureListener() { public void operationComplete(ChannelFuture f) throws Exception { // Log.d(Config.TAG, "isDone:" + f.isDone() + " isSuccess:" + f.isSuccess() + // " cause" + f.cause() + " isCancelled" + f.isCancelled()); if (f.isSuccess()) { Log.d(Config.TAG, "重新连接服务器成功"); } else { Log.d(Config.TAG, "重新连接服务器失败"); // 3秒后重新连接 f.channel().eventLoop().schedule(new Runnable() { @Override public void run() { doConnect(); } }, 3, TimeUnit.SECONDS); } } }; } // 连接到服务端 public static void doConnect() { Log.d(TAG, "doConnect"); ChannelFuture future = null; try { future = bootstrap.connect(new InetSocketAddress( serverIP, port)); future.addListener(channelFutureListener); } catch (Exception e) { e.printStackTrace(); //future.addListener(channelFutureListener); Log.d(TAG, "关闭连接"); } } }
@Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { Log.d(Config.TAG, "与服务器断开连接服务器"); super.channelInactive(ctx); MsgHandle.getInstance().channel = null; //重新连接服务器 ctx.channel().eventLoop().schedule(new Runnable() { @Override public void run() { MyClient.doConnect(); } }, 2, TimeUnit.SECONDS); ctx.close(); }