Netty多客户端连接服务端

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.function.Consumer;
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 com.xxx.radarflow.utils.Decoder;
public class NettyClient {
   public static EventLoopGroup eventLoopGroup;
   public static Bootstrap bootstrap;
   //连接失败集合
   public static CopyOnWriteArraySet<String> falseConnectSet = new CopyOnWriteArraySet();

       

/**
     * Netty初始化配置
     */
    {
        eventLoopGroup = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {

                        socketChannel.pipeline().addLast(new Decoder());
//                        socketChannel.pipeline().addLast(new Encoder());
                        socketChannel.pipeline().addLast(new NettyClientHandler());
                    }
                });

        // 异步持续监听连接失败的地址
        CompletableFuture.runAsync(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        if (falseConnectSet.size() != 0) {
                            // 循环集合内元素
                            falseConnectSet.forEach(new Consumer<String>() {
                                @Override
                                public void accept(String s) {
                                    String[] strings = s.split(":");
                                    Map map = new HashMap(2);
                                    map.put("IP", strings[0]);
                                    map.put("PORT", strings[1]);
                                    connectServer(map);
                                }
                            });
                        }
                        Thread.sleep(3000);
                    } catch (Exception e) {
//                        logger.error("Netty初始化配置监听地址出现异常");
//                        errorlogger.error("Netty初始化配置监听地址出现异常");
                        e.printStackTrace();
                    }
                }
            }
        });
    }

        

/**
 * 服务连接
 *
 * @param map
 */
private void connectServer(Map<String, Object> map) {
    // 获取地址及端口
    String host = (String) map.get("IP");
    Object portObj = map.get("PORT");
    int port = Integer.valueOf((String) portObj);
    // 异步连接tcp服务端
    bootstrap.remoteAddress(host, port).connect().addListener((ChannelFuture futureListener) -> {
        if (!futureListener.isSuccess()) {
            System.out.println(host + ":" + port + "连接失败!!!!!!!! 当前时间:" + new Date());
            futureListener.channel().close();
            // 连接失败信息插入Set
            falseConnectSet.add(host + ":" + port);
        } else {
            System.out.println(host + ":" + port + "连接成功,当前时间:" + new Date());
            // 连接成功信息从Set拔除
            falseConnectSet.remove(host + ":" + port);
        }
    });
}
/**
 * 初始化方法
 */
@PostConstruct
public void initialize() {
    Properties serial = null;
    try {
        serial = utils.readProperties("application.properties");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String northip = serial.getProperty("northip");
    String northport = serial.getProperty("northport");

    String eastip = serial.getProperty("eastip");
    String eastport = serial.getProperty("eastport");

    String southip = serial.getProperty("southip");
    String southport = serial.getProperty("southport");

    String westip = serial.getProperty("westip");
    String westport = serial.getProperty("westport");
    // 查询地址及端口 ..................................
    Map map1 = new HashMap(2);
    map1.put("IP", northip);
    map1.put("PORT", northport);
    Map map2 = new HashMap(2);
    map2.put("IP", eastip);
    map2.put("PORT", eastport);
    Map map3 = new HashMap(2);
    map3.put("IP", southip);
    map3.put("PORT", southport);
    Map map4 = new HashMap(2);
    map4.put("IP", westip);
    map4.put("PORT", westport);
    // ..............................................

    connectServer(map1);
    connectServer(map2);
    connectServer(map3);
    connectServer(map4);
}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值