导包
数据初始化
public class NettyServer {
public static Map<String, Channel> getMap() {
return map;
}
public static void setMap(Map<String, Channel> map) {
NettyServer.map = map;
}
private static Map<String, Channel> map = new ConcurrentHashMap<String, Channel>();
public void bind(int port) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup(); //bossGroup就是parentGroup,是负责处理TCP/IP连接的
EventLoopGroup workerGroup = new NioEventLoopGroup(); //workerGroup就是childGroup,是负责处理Channel(通道)的I/O事件
ServerBootstrap sb = new ServerBootstrap();
sb.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG, 128) //初始化服务端可连接队列,指定了队列的大小128
.childOption(ChannelOption.SO_KEEPALIVE, true) //保持长连接
.childHandler(new ChannelInitializer<SocketChannel>() { // 绑定客户端连接时候触发操作
@Override
protected void initChannel(SocketChannel sh) throws Exception {
sh.pipeline()
// .addLast( new MessagePacketDecoder()) //解码request
// .addLast(new MessagePacketEncoder()) //编码response
.addLast(new HelloServerHa