1. public class ProtoBufServer {
    2. public void bind(int port) throws Exception {
    3. // 配置服务端的NIO线程组
    4. EventLoopGroup bossGroup = new NioEventLoopGroup();
    5. EventLoopGroup workerGroup = new NioEventLoopGroup();
    6. try {
    7. ServerBootstrap b = new ServerBootstrap();
    8. b.group(bossGroup, workerGroup)
    9. .channel(NioServerSocketChannel.class)
    10. .option(ChannelOption.SO_BACKLOG, 100)
    11. .childHandler(new ChannelInitializer<SocketChannel>() {
    12. @Override
    13. public void initChannel(SocketChannel ch) {
    14. /*去除消息长度部分,同时根据这个消息长度读取实际的数据*/
    15. ch.pipeline().addLast(new ProtobufVarint32FrameDecoder());
    16. ch.pipeline().addLast(new ProtobufDecoder(PersonProto.Person.getDefaultInstance()));
    17. ch.pipeline().addLast(new ProtoBufServerHandler());
    18. }
    19. });
    20. // 绑定端口,同步等待成功
    21. ChannelFuture f = b.bind(port).sync();
    22. System.out.println("init start");
    23. // 等待服务端监听端口关闭
    24. f.channel().closeFuture().sync();
    25. } finally {
    26. // 优雅退出,释放线程池资源
    27. bossGroup.shutdownGracefully();
    28. workerGroup.shutdownGracefully();
    29. }
    30. }
    31. public static void main(String[] args) throws Exception {
    32. int port = 8080;
    33. new ProtoBufServer().bind(port);
    34. }
    35. }