需求:
所用接口说明:
当IdleStateEvent产生后,会传递给管道的下一个handler,通过调用下一个handler的userEventTiggered,在该方法中区处理IdleStateEvent(读空闲,写空闲,读写空闲)
服务端代码:
package com.example.demo.heartBeat;
import com.example.demo.chat.chatServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import java.util.concurrent.TimeUnit;
public class server {
private int port;
public server(int port){
this.port=port;
}
public void run () throws Exception {
EventLoopGroup workGroup= new NioEventLoopGroup();
EventLoopGroup boosGroup=new NioEventLoopGroup();
try{
ServerBootstrap bootstrap=new ServerBootstrap();
bootstrap.group(boosGroup,workGroup)
.channel(NioServerSocketChannel.class)//使用NioServerSocketChannel,作为服务器的通道实现
.option(ChannelOption.SO_BACKLOG,128)//设置线程队列的连接个数
.childOption(ChannelOption.SO_KEEPALIVE,true)//设置保持活动连接状态
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline=socketChannel.pipeline();
//加入一个netty提供的IdleStateHandler
pipeline.addLast(new IdleStateHandler(3,5,7, TimeUnit.SECONDS));
//自定义处理
pipeline.addLast("myHandler",new serverHandler());
}
});
ChannelFuture future=bootstrap.bind(this.port).sync();
future.channel().closeFuture().sync();
}finally {
workGroup.shutdownGracefully();;
boosGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
new server(6668).run();
}
}
handler:
package com.example.demo.heartBeat;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
public class serverHandler extends SimpleChannelInboundHandler {
@Override
protected void messageReceived(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if(evt instanceof IdleStateEvent){
//将evt向下转型IdleStateEvent
IdleStateEvent event=(IdleStateEvent)evt;
String eventType=null;
switch (event.state()){
case READER_IDLE:
eventType="读空闲";break;
case WRITER_IDLE:
eventType="写空闲";break;
case ALL_IDLE:
eventType="读写空闲";break;
}
System.out.println(ctx.channel().remoteAddress()+"超时时间--"+eventType);
}
}
}
再用前面写过的clien进行连接,效果