netty9092端口號重複,改爲9096就好了
package com.reachauto.vspcloud.common.netty.server;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;
@Slf4j
@Component
public class TimeServer {
public TimeServer(){}
public void bind(InetSocketAddress address) {
// 配置服務端的 NIO 線程池,用於網絡事件處理,實質上他們就是 Reactor 線程組
// bossGroup 用於服務端接受客戶端連接,workerGroup 用於進行 SocketChannel 網絡讀寫
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
// ServerBootstrap 是 Netty 用於啓動 NIO 服務端的輔助啓動類,用於降低開發難度
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.localAddress(address)
.option(ChannelOption.SO_BACKLOG, 1024)
.childHandler(new ChildChannelHandler());
ServerBootstrap sb = new ServerBootstrap();
sb.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.localAddress(9092)
.option(ChannelOption.SO_BACKLOG, 1024)
.childHandler(
new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch){
ch.pipeline().addLast(new HealthExaminationHandler());
}
}
);
// 服務器啓動輔助類配置完成後,調用 bind 方法綁定監聽端口,調用 sync 方法同步等待綁定操作完成
ChannelFuture f = b.bind(address).sync();
ChannelFuture fb = sb.bind(9092).sync();
if (log.isInfoEnabled()) {
log.info(Thread.currentThread().getName() + ",服務器開始監聽端口,等待客戶端連接.........");
}
// 下面會進行阻塞,等待服務器連接關閉之後 main 方法退出,程序結束
f.channel().closeFuture().sync();
fb.channel().closeFuture().sync();
} catch (InterruptedException e) {
if (log.isErrorEnabled()) {
log.error("TimeServer-bind報錯:" + e);
}
} finally {
// 優雅退出,釋放線程池資源
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
private ByteBuf[] lineDelimiter() {
return new ByteBuf[]{Unpooled.wrappedBuffer(new byte[]{'@', '!', 13, 10})};
}
@Override
protected void initChannel(SocketChannel arg0) {
if (log.isInfoEnabled()) {
log.info("初始化通道.........." + arg0.remoteAddress());
}
//改爲三分鐘心跳
arg0.pipeline().addLast(new IdleStateHandler(3, 0, 0, TimeUnit.MINUTES));
arg0.pipeline().addLast(new DelimiterBasedFrameDecoder(8192, lineDelimiter()));
arg0.pipeline().addLast(new TimeServerHandler());
}
}
}