需求描述
当服务器3秒没有发生读事件;或5秒没有发生写事件;或7秒没有发生读写事件。
服务器得到监听并且让客户端下线。
环境
dk8
netty
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.20.Final</version>
</dependency>
代码
Client.java
package com.lhh.demo.netty.chartgroup;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import java.util.Scanner;
public class Client {
private String host = "localhost";
private int port = 8888;
public Client(){
NioEventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.handler(new ClientChannelInitial());
ChannelFuture sync = bootstrap.connect(host, port).sync();
Channel channel = sync.channel();
System.out.println(channel.localAddress()+"is ready");
Scanner scanner = new Scanner(System.in);
while(scanner.hasNextLine()){
String s = scanner.nextLine();
channel.writeAndFlush(s);
}
channel.closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
group.shutdownGracefully();
}
}
class ClientChannelInitial extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("myStringEncoder",new StringEncoder());
pipeline.addLast("myStringDecoder",new StringDecoder());
pipeline.addLast("myClientHandler",new ClientHandler());
}
}
class ClientHandler extends SimpleChannelInboundHandler<String>{
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println(msg);
}
}
public static void main(String[] args) {
Client client = new Client();
}
}
Server.java
package com.lhh.demo.netty.heartbeat;
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.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;
public class Server {
public static void main(String[] args) {
NioEventLoopGroup boos = new NioEventLoopGroup();
NioEventLoopGroup worker = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(boos,worker)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//3秒没有读,5秒没有写,7秒没有读和写
//当发生事件会吧事件(IdleStateEvent)传给下一个handler
pipeline.addLast(new IdleStateHandler(3,5,7, TimeUnit.SECONDS));
pipeline.addLast(new MyHandler());
}
});
ChannelFuture sync = bootstrap.bind(8888).sync();
sync.channel().closeFuture().sync();
} catch (Exception e) {
e.printStackTrace();
} finally {
boos.shutdownGracefully();
worker.shutdownGracefully();
}
}
static class MyHandler extends ChannelInboundHandlerAdapter{
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
super.userEventTriggered(ctx, evt);
if(evt instanceof IdleStateEvent){
IdleStateEvent event = (IdleStateEvent) evt;
String msg = "";
switch (event.state()) {
//读空闲
case READER_IDLE:
msg = "读空闲";
break;
//写空闲
case WRITER_IDLE:
msg = "写空闲";
break;
//读写空闲
case ALL_IDLE:
msg = "读写空闲";
break;
}
System.out.println(LocalDateTime.now()+";发生了:"+msg);
//发生空闲 关闭通道
ctx.close();
}
}
}
}