1. public class ProtoBufClient {
    2. public void connect(int port, String host) throws Exception {
    3. // 配置客户端NIO线程组
    4. EventLoopGroup group = new NioEventLoopGroup();
    5. try {
    6. Bootstrap b = new Bootstrap();
    7. b.group(group)
    8. .channel(NioSocketChannel.class)
    9. .option(ChannelOption.TCP_NODELAY, true)
    10. .handler(new ChannelInitializer<SocketChannel>() {
    11. @Override
    12. public void initChannel(SocketChannel ch)
    13. throws Exception {
    14. /*加一个消息长度,由netty自动计算 粘包半包问题*/
    15. ch.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
    16. /*负责编码,序列化*/
    17. ch.pipeline().addLast(new ProtobufEncoder());
    18. ch.pipeline().addLast(new ProtoBufClientHandler());
    19. }
    20. });
    21. ChannelFuture f = b.connect(host, port).sync();
    22. f.channel().closeFuture().sync();
    23. } finally {
    24. // 优雅退出,释放NIO线程组
    25. group.shutdownGracefully();
    26. }
    27. }
    28. public static void main(String[] args) throws Exception {
    29. int port = 8080;
    30. new ProtoBufClient().connect(port, "127.0.0.1");
    31. }
    32. }