netty客户端实现断开重新连接

客户端代码

import com.jetch.collet.utils.PropertiesUtils;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.concurrent.TimeUnit;


public class HeartBeatClient implements Runnable {
    private Channel channel;
    private EventLoopGroup group = new NioEventLoopGroup();

    @Override
    public void run() {
        Bootstrap bootstrap = new Bootstrap();
        connect(bootstrap, group);

    }


    public void connect(Bootstrap bootstrap, EventLoopGroup loopGroup) {
        ChannelFuture f = null;
        /**
         * 创建客户端  链接远程主机  实时发送当前程序的状态
         */
        try {

            bootstrap.group(loopGroup).channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new StringEncoder());
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new HeartBeatClientHanlder(HeartBeatClient.this));
                        }
                    });
            bootstrap.remoteAddress(PropertiesUtils.MSTSC_HEART_BEAT_IP, PropertiesUtils.MSTSC_HEART_BEAT_PORT);
            //channel = bootstrap.connect(PropertiesUtils.MSTSC_HEART_BEAT_IP, PropertiesUtils.MSTSC_HEART_BEAT_PORT).sync().channel();
            //channel.closeFuture().sync();
            f = bootstrap.connect().addListener((ChannelFuture futureListener) -> {
                final EventLoop eventLoop = futureListener.channel().eventLoop();
                if (!futureListener.isSuccess()) {
                    System.err.println("客户端已启动,与服务端建立连接失败,10s之后尝试重连!");
                    eventLoop.schedule(() -> connect(new Bootstrap(), eventLoop), 10, TimeUnit.SECONDS);
                } else {
                    System.out.println("客户端已启动成功,开始登录服务端");
                    HeartBeatClientHanlder.flag = true;
                    // 可以在这发送登录成功的消息给server
                    //futureListener.channel().writeAndFlush(Unpooled.copiedBuffer("msg!!!", CharsetUtil.UTF_8));

                }
            });
        } catch (Exception e) {
            System.err.println("连接客户端失败,error:");
        }

    }
}

在handler中  如果连接断开  发起重新连接

import com.jetch.collet.utils.PropertiesUtils;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author cy
 * @date 2022/4/11
 **/
public class HeartBeatClientHanlder extends SimpleChannelInboundHandler<String> {

    public static boolean flag=true;

    private HeartBeatClient nettyClient;

    public HeartBeatClientHanlder(HeartBeatClient nettyClient) {
        this.nettyClient = nettyClient;
    }

    int num=1;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
    //延时任务 每隔几秒发送心跳检测包 ScheduledExecutorService scheduledExecutorService
= Executors.newSingleThreadScheduledExecutor(new ThreadFactoryImpl( "TestScheduledThread")); scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { if(flag){ System.out.println("===="); Channel channel = ctx.channel(); channel.writeAndFlush("heart beat=="+ PropertiesUtils.DETAIL_ID+"=="+num); num=2; } } }, 1L, 5, TimeUnit.SECONDS); } @Override protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception { }
  //连接断开 发起从新连接请求 @Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception { System.err.println("运行中断开重连。。。"); flag=false; nettyClient.connect(new Bootstrap() ,ctx.channel().eventLoop()); } }

 

创建守护线程

public class ThreadFactoryImpl implements ThreadFactory {
    private final AtomicLong threadIndex = new AtomicLong(0);
    private final String threadNamePrefix;
    private final boolean daemon;

    public ThreadFactoryImpl(final String threadNamePrefix) {
        this(threadNamePrefix, false);
    }

    public ThreadFactoryImpl(final String threadNamePrefix, boolean daemon) {
        this.threadNamePrefix = threadNamePrefix;
        this.daemon = daemon;
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r, threadNamePrefix + this.threadIndex.incrementAndGet());
        thread.setDaemon(daemon);
        return thread;
    }
}

 

posted @ 2022-05-07 11:17  转身瞬间  阅读(1543)  评论(0)    收藏  举报