Skip to content

Commit

Permalink
IdleStateHandler及心跳机制的使用
Browse files Browse the repository at this point in the history
  • Loading branch information
1263919792@qq.com committed Jul 24, 2019
1 parent 177e92d commit c998b11
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 3 deletions.
3 changes: 2 additions & 1 deletion src/main/java/netty_demo/nettytimeout/ClientHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Excep

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ctx.channel().writeAndFlush(Unpooled.copiedBuffer("nihao", CharsetUtil.UTF_8));
ByteBuf byteBuf = Unpooled.copiedBuffer("nihao", CharsetUtil.UTF_8);
ctx.channel().writeAndFlush(byteBuf);
}

@Override
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/netty_demo/nettytimeout/EchoServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ private void start() throws Exception {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//IdleStateHandler监控服务端读写超时时间
ch.pipeline().addLast(new IdleStateHandler(10, 8, 7, TimeUnit.SECONDS));
ch.pipeline().addLast(new IdleStateHandler(0, 0, 5, TimeUnit.SECONDS));
ch.pipeline().addLast(new EchoServerHandler());
}
});
Expand Down
11 changes: 10 additions & 1 deletion src/main/java/netty_demo/nettytimeout/EchoServerHandler.java
Original file line number Diff line number Diff line change
@@ -1,14 +1,23 @@
package netty_demo.nettytimeout;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;

public class EchoServerHandler extends ChannelInboundHandlerAdapter {

@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

if (evt instanceof IdleStateEvent) {
ctx.writeAndFlush(Unpooled.copiedBuffer("是否断开连接了", CharsetUtil.UTF_8))
.addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
}

/*if (evt instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) evt;
String eventType = null;
Expand All @@ -28,6 +37,6 @@ public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exc
}
System.out.println(ctx.channel().remoteAddress() + " 超时时间 : " + eventType);
}
}*/
}
}

0 comments on commit c998b11

Please sign in to comment.