netty 服务端断开连接后重新连接

问题

刚开始使用netty,并未考虑服务端网络问题,但是今天发现有几次出现客户端发送成功,但是服务端未收到消息的情况,这才开始考虑客户端重连问题。

方案

netty本身提供断开连接通知,客户端需要在收到通知后,编写代码进行重新连接即可。

步骤

  1. 自定义处理类NettyClientHandler继承ChannelInboundHandlerAdapter,实现其方法,如下图:
    @Override
    public void channelInactive(ChannelHandlerContext ctx){
        logger.error("掉线了...");
        logger.error("channelInactive:{}", ctx.channel().localAddress());
        try{
            super.channelInactive(ctx);
            nettyClient.connectAsync();
            logger.error("重连完成");
        }catch (Exception e){
            logger.error("重连失败:{}", ExceptionUtils.getStackTrace(e));
        }

    }

2.connectAsync方法实现真正的重连:

    public void connectAsync() {
        logger.error("尝试连接到服务端: {}:{}",host,port);
        try {
            ChannelFuture channelFuture = bootstrap.connect(host, port);
            channelFuture.addListener((ChannelFutureListener) future -> {
                if (!future.isSuccess()) {
                    logger.error("等待下一次重连");
                    ScheduledFuture scheduledFuture = null;
                    try{
                        scheduledFuture=future.channel().eventLoop().schedule(() -> {
                            logger.error("scheduler------------------start");
                            connectAsync();
                            logger.error("scheduler------------------end");
                        }, 1, TimeUnit.SECONDS);
                        logger.error("end:{}",scheduledFuture.isDone());
                    }catch (Exception e){
                        logger.error("error:{}",ExceptionUtils.getStackTrace(e));
                    }

                } else {
                    logger.error("Netty client started !!! {} connect to server", channel.localAddress());
                    channel = future.channel();
                }
            });
        }catch (Exception e){
            logger.error("重连出错:{}",ExceptionUtils.getStackTrace(e));
        }

    }

netty都是异步操作,连接之后,需要添加监听,在监听内部获取是否连接成功的通知,如果失败,则使用异步的线程重新执行该方法,直到成功;成功则直接退出。

问题

目前,还未考虑:在重连的过程中,客户端还是未发送消息给服务端,需要在发现断开连接之后,则停止消息发送,直到连接成功!!

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Netty中,可以使用ChannelFutureListener来监听连接的状态,当连接断开时,可以在监听器中进行重连操作。以下是一个简单的示例代码: ```java public class NettyClient { private final String host; private final int port; private final EventLoopGroup group; private final Bootstrap bootstrap; public NettyClient(String host, int port) { this.host = host; this.port = port; this.group = new NioEventLoopGroup(); this.bootstrap = new Bootstrap() .group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { // 添加自定义处理器 ch.pipeline().addLast(new MyHandler()); } }); } public void start() { // 连接服务器 ChannelFuture future = bootstrap.connect(host, port); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { System.out.println("连接成功"); } else { System.out.println("连接失败"); // 进行重连操作 future.channel().eventLoop().schedule(new Runnable() { @Override public void run() { start(); } }, 1, TimeUnit.SECONDS); } } }); } public void stop() { group.shutdownGracefully(); } public static void main(String[] args) throws InterruptedException { NettyClient client = new NettyClient("localhost", 8888); client.start(); Thread.sleep(3000); client.stop(); } } ``` 在上述代码中,我们在连接状态监听器中进行了重连操作。当连接失败时,我们使用eventLoop的schedule方法在1秒后再次进行连接。这样就可以实现对客户端连接重连

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lixiaolinzq

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值