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