package io.netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class NettyServer {
public static void main(String[] args) throws InterruptedException {
//创建一个BoosGroup WorkerGroup
//boosgroup只处理连接请求
EventLoopGroup boosGroup = new NioEventLoopGroup(1);
//真正与客户端数据打交道
EventLoopGroup workerGroup = new NioEventLoopGroup(8);
//创建服务器启动
ServerBootstrap serverBootstrap = new ServerBootstrap();
//设置二个线程组
serverBootstrap.group(boosGroup,workerGroup).channel(NioServerSocketChannel.class)
//设置阻塞队列128
.option(ChannelOption.SO_BACKLOG,128)
//设置保持活动连接状态
.childOption(ChannelOption.SO_KEEPALIVE,true)
//给 workerGroup 中的 eventLoop 的pipeline 添加 事件处理器
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
//管理所有的客户端socketchannel
System.out.println("客户端的sockeChannel hashcode"+socketChannel.hashCode());
socketChannel.pipeline().addLast(new NettyServerHandler());
}
});
System.out.println("server is ready");
//服务端绑定一个端口 并且同步 启动
ChannelFuture channelFuture = serverBootstrap.bind(6668).sync();
//注册关心的事件
channelFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture channelFuture) throws Exception {
if(channelFuture.isSuccess()){
System.out.println("监听端口6668成功");
}else {
System.out.println("监听端口6668失败");
}
}
});
//关闭通道进行事件监听
channelFuture.channel().closeFuture().sync();
//优雅的关闭
boosGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}