1. package net.xdclass.echo;
    2. import io.netty.bootstrap.ServerBootstrap;
    3. import io.netty.channel.ChannelFuture;
    4. import io.netty.channel.ChannelInitializer;
    5. import io.netty.channel.EventLoopGroup;
    6. import io.netty.channel.nio.NioEventLoopGroup;
    7. import io.netty.channel.socket.SocketChannel;
    8. import io.netty.channel.socket.nio.NioServerSocketChannel;
    9. public class EchoServer {
    10. private int port;
    11. public EchoServer(int port){
    12. this.port = port;
    13. }
    14. /**
    15. * 启动流程
    16. */
    17. public void run() throws InterruptedException {
    18. //配置服务端线程组
    19. EventLoopGroup bossGroup = new NioEventLoopGroup();
    20. EventLoopGroup workGroup = new NioEventLoopGroup();
    21. try{
    22. ServerBootstrap serverBootstrap = new ServerBootstrap();
    23. serverBootstrap.group(bossGroup, workGroup)
    24. .channel(NioServerSocketChannel.class)
    25. .childHandler(new ChannelInitializer<SocketChannel>() {
    26. protected void initChannel(SocketChannel ch) throws Exception {
    27. ch.pipeline().addLast(new EchoServerHandler());
    28. }
    29. });
    30. System.out.println("Echo 服务器启动ing");
    31. //绑定端口,同步等待成功
    32. ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
    33. //等待服务端监听端口关闭
    34. channelFuture.channel().closeFuture().sync();
    35. }finally {
    36. //优雅退出,释放线程池
    37. workGroup.shutdownGracefully();
    38. bossGroup.shutdownGracefully();
    39. }
    40. }
    41. public static void main(String [] args) throws InterruptedException {
    42. int port = 8080;
    43. if(args.length > 0){
    44. port = Integer.parseInt(args[0]);
    45. }
    46. new EchoServer(port).run();
    47. }
    48. }