EchoServer

  1. public class EchoServer {
  2. private final int port;
  3. public EchoServer(int port) {
  4. this.port = port;
  5. }
  6. public static void main(String[] args) throws InterruptedException {
  7. EchoServer echoServer = new EchoServer(9999);
  8. System.out.println("服务器即将启动");
  9. echoServer.start();
  10. System.out.println("服务器关闭");
  11. }
  12. public void start() throws InterruptedException {
  13. final EchoServerHandler serverHandler = new EchoServerHandler();
  14. EventLoopGroup group = new NioEventLoopGroup();/*线程组*/
  15. try {
  16. ServerBootstrap b = new ServerBootstrap();/*服务端启动必须*/
  17. b.group(group)/*将线程组传入*/
  18. .channel(NioServerSocketChannel.class)/*指定使用NIO进行网络传输*/
  19. .localAddress(new InetSocketAddress(port))/*指定服务器监听端口*/
  20. /*服务端每接收到一个连接请求,就会新启一个socket通信,也就是channel,
  21. 所以下面这段代码的作用就是为这个子channel增加handle*/
  22. .childHandler(new ChannelInitializer<SocketChannel>() {
  23. @Override
  24. protected void initChannel(SocketChannel ch) throws Exception {
  25. ch.pipeline().addLast(serverHandler);/*添加到该子channel的pipeline的尾部*/
  26. }
  27. });
  28. ChannelFuture f = b.bind().sync();/*异步绑定到服务器,sync()会阻塞直到完成*/
  29. System.out.println("服务器启动完成,等待客户端的连接和数据.....");
  30. f.channel().closeFuture().sync();/*阻塞直到服务器的channel关闭*/
  31. } finally {
  32. group.shutdownGracefully().sync();/*优雅关闭线程组*/
  33. }
  34. }
  35. }