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