1. 程式人生 > 實用技巧 >Netty的心跳機制

Netty的心跳機制

在Netty中,會定期傳送一個數據包,也就是“心跳”,來確定客戶端和服務端是否連線。該機制通過IdleStateHandler處理器和自定義的handleruserEventTriggered方法來實現,具體的例項如下圖:

Server:

public class Server {
public static void main(String[] args) throws InterruptedException {
//建立兩個執行緒組
EventLoopGroup boss=new NioEventLoopGroup(1);
EventLoopGroup worker=new NioEventLoopGroup();
try{
ServerBootstrap bootstrap=new ServerBootstrap()
.group(boss,worker)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
//給bossgruop新增一個日誌處理器
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
//加入netty提供的 IdLeStateHandler
//處理空閒狀態的處理器
//三個引數:1.表示多久沒有讀 會發送一個心跳檢測包檢測是否連結
//2.表示多久沒有寫 會發送一個心跳檢測包檢測是否連結 3.多長時間沒有讀寫 會發送一個心跳檢測包檢測是否連結
//當IdLeStateEvent觸發後 會傳遞給下一個handler處理
//通過呼叫下一個handler的userEventTiggered 在該方法中處理
pipeline.addLast(new IdleStateHandler(3,5,7, TimeUnit.SECONDS));
//加入對一個空閒檢測進行進一步處理的handler
pipeline.addLast(new ServerHandler());
}
});
//啟動伺服器
ChannelFuture channelFuture = bootstrap.bind(8848).sync();
channelFuture.channel().closeFuture().sync();
}
finally {
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}
}
ServerHandler:
public class ServerHandler extends ChannelInboundHandlerAdapter {
/**
* @param ctx 上下文
* @param evt 事件
* @throws Exception
*/
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
//轉型
IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
String eventType = null;
switch (idleStateEvent.state()) {
case READER_IDLE:
eventType = "讀空閒";
break;
case WRITER_IDLE:
eventType = "寫空閒";
break;
case ALL_IDLE:
eventType = "讀寫空閒";
break;
}
System.out.println(ctx.channel().remoteAddress() + eventType);
//如果空閒發生 關閉通道
ctx.channel().close();
}
}
}