断线重连功能的Netty客户端程序示例。它将不断地尝试重新连接到服务器,如果连接被意外中断,将自动重新连接。

public class NettyClient {
    private static final int MAX_RETRY = 5;
    private static final int READ_TIMEOUT_SECONDS = 180;

    public static void main(String[] args) {
        String host = "localhost";
        int port = 9090;

        NioEventLoopGroup group = new NioEventLoopGroup();
        int retry = 0;
        while (retry < MAX_RETRY) {
            try {
                Bootstrap bootstrap = new Bootstrap();
                bootstrap.group(group)
                        .channel(NioSocketChannel.class)
                        .handler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            public void initChannel(SocketChannel ch) {
                                ch.pipeline().addLast(new IdleStateHandler(0, 0, READ_TIMEOUT_SECONDS, TimeUnit.SECONDS));
                                ch.pipeline().addLast(new ClientHandler());
                            }
                        });

                ChannelFuture future = bootstrap.connect(host, port).sync();
                log.info("客户端连接到" + host + ":" + port);

                String message = "Hello, server!";
                ByteBuf buffer = future.channel().alloc().buffer(message.length());
                buffer.writeBytes(message.getBytes());

                future.channel().writeAndFlush(buffer);
                log.info("Message sent to server: " + message);

                future.channel().closeFuture().sync();
            } catch (Exception e) {
                System.err.println("Failed to connect to " + host + ":" + port);
                retry++;
                try {
                    // Wait for 10 seconds before reconnecting
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException interruptedException) {
                    Thread.currentThread().interrupt();
                }
            }
        }
        log.info("已达到最大重试次数,请退出。");
        group.shutdownGracefully();
    }

    private static class ClientHandler extends ChannelInboundHandlerAdapter {
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            ByteBuf buf = (ByteBuf) msg;
            String message = buf.toString(io.netty.util.CharsetUtil.UTF_8);
            log.info("从服务器接收到消息: " + message);
        }

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (evt instanceof IdleStateEvent) {
                IdleStateEvent event = (IdleStateEvent) evt;
                if (event.state() == IdleStateEvent.READER_IDLE_STATE_EVENT.state()) {
                    System.err.println("未收到的数据 " + READ_TIMEOUT_SECONDS + " 秒,关闭频道。");
                    ctx.close();
                }
            }
        }

        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            System.err.println("Connection lost, retrying to connect...");
            ctx.channel().eventLoop().schedule(new Runnable() {
                @Override
                public void run() {
                    NettyClient.main(new String[0]);
                }
            }, 10, TimeUnit.SECONDS);
            super.channelInactive(ctx);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            cause.printStackTrace();
            ctx.close();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值