Demo/src/main/java/com/example/demo/Service/nettyServerHeart.java

101 lines
3.4 KiB
Java

package com.example.demo.Service;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
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.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.TimeUnit;
@Slf4j
public class nettyServerHeart {
private final int port;
public nettyServerHeart(int port) {
this.port = port;
}
public void start() throws InterruptedException {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);//线程
EventLoopGroup workerGroup = new NioEventLoopGroup();//8
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG,128)
.childOption(ChannelOption.SO_KEEPALIVE,true)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline();
log.info("客户端channel初始化");
p.addLast(new IdleStateHandler(4,0,0, TimeUnit.SECONDS));
p.addLast(new nettyServerHandler2());
}
});
ChannelFuture f = b.bind(port).sync();//成功之后在执行
log.info("服务启动成功!");
f.addListener((ChannelFutureListener)future -> log.info("监听端口:{}",future.isSuccess()));
f.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws InterruptedException {
new nettyServerHeart(8888).start();
}
}
@Slf4j
class nettyServerHandler2 extends ChannelInboundHandlerAdapter {
int i = 0;
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
i++;
ByteBuf in = (ByteBuf)msg;
System.out.println("Received message: " +in.toString(io.netty.util.CharsetUtil.UTF_8));
System.out.println();
//ctx.channel().writeAndFlush(Unpooled.copiedBuffer("Hello from Netty Server",CharsetUtil.UTF_8));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if(evt instanceof IdleStateEvent){
IdleStateEvent idleStateEvent = (IdleStateEvent)evt;
switch (idleStateEvent.state()){
case ALL_IDLE:
log.error("读写都空闲");
break;
case READER_IDLE:
log.error("读空闲");
break;
case WRITER_IDLE:
log.error("写空闲");
break;
default:
System.out.println("default!");
}
}
}
}