Netty 创建服务端代码记录
@Slf4j
@Component
public class NettyServerBootstrap {
private Channel serverChannel;
private static final int DEFAULT_PORT = 9999;
private static EventLoopGroup bossGroup = null;
private static EventLoopGroup workGroup = null;
public boolean start() {
return start(DEFAULT_PORT);
}
public boolean start(int port) {
bossGroup = new NioEventLoopGroup();
workGroup = new NioEventLoopGroup();
ServerBootstrap bootstrap = new ServerBootstrap();
try {
bootstrap.group(bossGroup, workGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 1024)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.childHandler(new ChildChannelHandler());
ChannelFuture future = bootstrap.bind(port).sync();
log.info("netty服务启动成功,ip:{},端口:{}", InetAddress.getLocalHost().getHostAddress(), port);
serverChannel = future.channel();
ThreadUtil.execute(() -> {
try {
future.channel().closeFuture().sync();
log.info("netty服务正常关闭成功,ip:{},端口:{}", InetAddress.getLocalHost().getHostAddress(), port);
} catch (InterruptedException | UnknownHostException e) {
e.printStackTrace();
} finally {
shutdown();
}
});
} catch (Exception e) {
e.printStackTrace();
log.error("netty服务异常,异常原因:{}", e.getMessage());
return false;
}
return true;
}
private static class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
log.info("初始化客户端id:{},远端ip:{}", ch.id(), ch.remoteAddress());
ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(ByteOrder.LITTLE_ENDIAN, Integer.MAX_VALUE, 2, 2, -4, 0, false));
ch.pipeline().addLast("decoder", new ByteArrayDecoder());
ch.pipeline().addLast("encoder", new ByteArrayEncoder());
ch.pipeline().addLast("nettyServerHandler", new NettyServerHandler());
}
}
public boolean close() {
if (serverChannel != null) {
serverChannel.close();
try {
serverChannel.closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
return false;
} finally {
shutdown();
serverChannel = null;
}
}
return true;
}
private void shutdown() {
workGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
@Slf4j
public class NettyServerHandler extends SimpleChannelInboundHandler<byte[]> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, byte[] msg) throws Exception {
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
ChannelId channelId = ctx.channel().id();
log.info("客户端id:{},断开连接,ip:{}", channelId, ctx.channel().remoteAddress());
super.handlerRemoved(ctx);
}
}