1. server
1 public class Server { 2 3 public static void main(String[] args) throws Exception { 4 System.out.println("Server is starting..."); 5 //1 创建线两个程组 6 EventLoopGroup bossGroup = new NioEventLoopGroup(); //一个是用于处理服务器端接收客户端连接的 7 EventLoopGroup workGroup = new NioEventLoopGroup(); //一个是进行网络通信的(网络读写的) 8 9 //2 创建辅助工具类,用于服务器通道的一系列配置 10 ServerBootstrap b = new ServerBootstrap(); 11 b.group(bossGroup, workGroup) //绑定俩个线程组 12 .channel(NioServerSocketChannel.class) //指定NIO的模式 13 .option(ChannelOption.SO_BACKLOG, 1024) //设置tcp缓冲区 14 .option(ChannelOption.SO_SNDBUF, 32*1024) //设置发送缓冲大小 15 .option(ChannelOption.SO_RCVBUF, 32*1024) //这是接收缓冲大小 16 .option(ChannelOption.SO_KEEPALIVE, true) //保持连接 17 .childHandler(new ChannelInitializer<SocketChannel>() {//服务端就是childHandler 18 @Override 19 protected void initChannel(SocketChannel socketChannel) throws Exception { 20 //3 在这里配置具体数据接收方法的处理 ChannelPipeline<<<添加到<<-ChannelHandler 21 socketChannel.pipeline().addLast(new ServerHandler()); 22 } 23 }); 24 25 //4 异步,进行绑定 服务端是bind,客户端是connect 26 ChannelFuture channelFuture = b.bind(8765).sync(); 27 //5 等待关闭 28 channelFuture.channel().closeFuture().sync(); // 阻塞用, 等价于Thread.sleep(Integer.MAX_VALUE) 29 30 bossGroup.shutdownGracefully(); 31 workGroup.shutdownGracefully(); 32 } 33 }