Netty 学习笔记3 客户端

Netty 学习笔记3 客户端

基本使用

  1. 创建引导类 Bootstrap 对象
// 负责启动客户端以及连接服务端
Bootstrap bootstrap = new Bootstrap();
  1. 使用 group 方法配置事件循环组
EventLoopGroup workerGroup = new NioEventLoopGroup();
bootstrap.group(workerGroup);
  1. 设置 channel 类型
// 指定线程模型,驱动着连接的数据读写
bootstrap.channel(NioSocketChannel.class);

// or EpollSocketChannel
// or KQueueSocketChannel
  1. 定义连接的业务处理逻辑
bootstrap.handler(new ChannelInitializer<Channel>() {
    @Override
    protected void initChannel(Channel channel) throws Exception {
        ChannelPipeline channelPipeline = channel.pipeline();
        channelPipeline.addLast(new EchoClientHandler());
    }
});
  1. 设置参数
// 表示连接的超时时间,超过这个时间还是建立不上的话则代表连接失败
bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
// 表示是否开启 TCP 底层心跳机制,true 为开启
bootstrap.option(ChannelOption.SO_KEEPALIVE, true)
// 表示是否开始 Nagle 算法,true 表示关闭,false 表示开启,
// 通俗地说,如果要求高实时性,有数据发送时就马上发送,就设置为 true 关闭,如果需要减少发送次数减少网络交互,就设置为 false 开启
bootstrap.option(ChannelOption.TCP_NODELAY, true)
  1. 连接服务端
ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 51001).sync();

// 或者这样
bootstrap.remoteAddress(new InetSocketAddress("127.0.0.1", 51001));
//bootstrap.remoteAddress("127.0.0.1", 51001);
ChannelFuture channelFuture = bootstrap.connect().sync();

// 监听关闭事件,阻塞
channelFuture.channel().closeFuture().sync();

失败重连

private static void connect(Bootstrap bootstrap, String host, int port, int retry) {
    bootstrap.connect(host, port).addListener(future -> {
        if (future.isSuccess()) {
            System.out.println("连接成功!");
        } else if (retry == 0) {
            System.err.println("重试次数已用完,放弃连接!");
        } else {
            // 第几次重连
            int order = (MAX_RETRY - retry) + 1;
            // 本次重连的间隔
            int delay = 1 << order;
            System.out.println("连接失败,第" + order + "次重连……");
            bootstrap.config().group().schedule(() -> connect(bootstrap, host, port, retry - 1), delay, TimeUnit.SECONDS);
        }
    });
}

完整示例

    private static final int MAX_RETRY = 5;

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(workerGroup);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.handler(new ChannelInitializer<Channel>() {
                @Override
                protected void initChannel(Channel channel) throws Exception {
                    ChannelPipeline channelPipeline = channel.pipeline();
                    channelPipeline.addLast(new EchoClientHandler());
                }
            });
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 51001).sync();
            connect(bootstrap, "127.0.0.1", 51001, MAX_RETRY);
        } finally {
            workerGroup.shutdownGracefully();
        }
    }

    private static void connect(Bootstrap bootstrap, String host, int port, int retry) {
        bootstrap.connect(host, port).addListener(future -> {
            if (future.isSuccess()) {
                System.out.println("连接成功!");
            } else if (retry == 0) {
                System.err.println("重试次数已用完,放弃连接!");
            } else {
                // 第几次重连
                int order = (MAX_RETRY - retry) + 1;
                // 本次重连的间隔
                int delay = 1 << order;
                System.out.println("连接失败,第" + order + "次重连……");
                bootstrap.config().group().schedule(() -> connect(bootstrap, host, port, retry - 1), delay, TimeUnit.SECONDS);
            }
        });
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值