Netty心跳机制
项目结构
Server
public class MyServer {
public static void main(String
[] args
) throws InterruptedException
{
NioEventLoopGroup bossGroup
= new NioEventLoopGroup();
NioEventLoopGroup workerGroup
= new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap
= new ServerBootstrap();
serverBootstrap
.group(bossGroup
,workerGroup
)
.channel(NioServerSocketChannel
.class)
.handler(new LoggingHandler(LogLevel
.INFO
))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch
) throws Exception
{
ChannelPipeline pipeline
= ch
.pipeline();
pipeline
.addLast(new IdleStateHandler(3,5,7, TimeUnit
.SECONDS
));
pipeline
.addLast(new MyServerHandler());
}
});
ChannelFuture channelFuture
= serverBootstrap
.bind(6666).sync();
channelFuture
.channel().closeFuture().sync();
}finally {
bossGroup
.shutdownGracefully();
workerGroup
.shutdownGracefully();
}
}
}
ServerHandler
public class MyServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void userEventTriggered(ChannelHandlerContext ctx
, Object evt
) throws Exception
{
if (evt
instanceof IdleStateEvent){
IdleStateEvent event
= (IdleStateEvent
) evt
;
String evenType
= null
;
switch (event
.state()){
case READER_IDLE
:
evenType
= "读空闲";
break;
case WRITER_IDLE
:
evenType
= "写空闲";
break;
case ALL_IDLE
:
evenType
= "读写空闲";
break;
}
System
.out
.println(ctx
.channel().remoteAddress() + "--超时事件--"+evenType
);
}
}
}
客户端这里就不写了直接使用上一个案例聊天室的客户端