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();
}
}
}
 
        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM