在上述例子的事件处理流上加上心跳连接
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//对ByteBuf数据流进行处理,转换成http的对象
pipeline.addLast(new HttpServerCodec());// Http消息编码解码
pipeline.addLast(new HttpObjectAggregator(64*1024));
pipeline.addLast(new IdleStateHandler(5, 0, 0)); //心跳
pipeline.addLast(new ChunkedWriteHandler());
pipeline.addLast(new SocketHandler());//自定义处理类
}
再在自定义的事件处理器上,重写心跳断开后的处理事件
//关闭连接
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) evt;
if (event.state() == IdleState.READER_IDLE) {
ctx.channel().close();
System.out.println("连接超时,将关闭链路");
}
} else {
super.userEventTriggered(ctx, evt);
}
}
效果
1连接上socket服务器
2在5秒之内可以正常通讯
3 5秒后触发断开方法断开链路,通讯中断