<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.20.Final</version>
</dependency>
package com.example.demo.controller.http;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
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.IdleStateHandler;
import java.util.concurrent.TimeUnit;
//服务端
public class MyServer {
public static void main(String[] args) throws InterruptedException {
EventLoopGroup boss=new NioEventLoopGroup();
EventLoopGroup worker=new NioEventLoopGroup();
try {
ServerBootstrap bootstrap=new ServerBootstrap();
bootstrap.group(boss,worker)
.channel(NioServerSocketChannel.class)
//对boss进行记录处理程序
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
// long readerIdleTime, 表示多长时间没有读 就发送一个心跳包检测是否连接
// long writerIdleTime, 表示多长时间没有写 就发送一个心跳包检测是否连接
// long allIdleTime 表示多长时间没有读写 就发送一个心跳包检测是否连接
pipeline.addLast(new IdleStateHandler(3,5,7, TimeUnit.SECONDS));
//当IdleStateEvent 触发后 就会传递给管道的一个处理程序去处理, userEventTiggered 在该方法中去处理
pipeline.addLast(new MyHandler());
}
});
//绑定端口
ChannelFuture sync = bootstrap.bind(7777).sync();
//监听关闭
sync.channel().closeFuture().sync();
}finally {
//优雅关闭
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}
}
package com.example.demo.controller.http;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
//服务端业务处理程序
public class MyHandler extends ChannelInboundHandlerAdapter {
//用户事件触发
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if(evt instanceof IdleStateEvent){
//向下转型
IdleStateEvent idleStateEvent=(IdleStateEvent) evt;
String msg="";
switch (idleStateEvent.state()){
case READER_IDLE:
msg="读空闲";
break;
case WRITER_IDLE:
msg="写空闲";
break;
case ALL_IDLE:
msg="读写空闲";
break;
}
System.out.println(ctx.channel().remoteAddress()+"---超时时间---"+msg);
System.out.println("服务器做自己的业务处理");
//关闭通道 就不会在进行心跳检测
// ctx.channel().close();
}
}
}
telnet 127.0.0.1 7777