package com.tcp.server;
import com.tcp.protobuf.NettyClientInitializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.stereotype.Component;
import java.net.InetSocketAddress;
import java.util.*;
import java.util.concurrent.TimeUnit;
@Component
public class TcpManyClient {
//多个tcp服务器的端口
private static List<Integer> PORTS = Arrays.asList(20000, 20001, 20002, 20003, 20004);
//多个tcp服务器的ip
private static List<String> HOSTS = Arrays.asList("127.0.0.1", "127.0.0.1", "127.0.0.1", "127.0.0.1", "127.0.0.1");
public static Map<Integer, ChannelFuture> channels = getChannel(HOSTS, PORTS);
/**
* 初始化Bootstrap
*/
public static final Bootstrap getBootstrap(EventLoopGroup group) {
if (null == group) {
group = new NioEventLoopGroup();
}
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.SO_KEEPALIVE, true);
bootstrap.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
// 添加自定义协议的编解码工具
pipeline.addLast(new IdleStateHandler(0, 30, 0, TimeUnit.SECONDS));
ch.pipeline().addLast(new SmartCarEncoder());
ch.pipeline().addLast(new SmartCarDecoder());
pipeline.addLast(new TcpClientHandler());
}
});
return bootstrap;
}
// 获取所有连接
public static final Map<Integer, ChannelFuture> getChannel(List<String> hosts, List<Integer> ports) {
Map<
netty4客户端连接多个不同的服务端
最新推荐文章于 2024-09-06 15:53:27 发布
本文介绍如何使用Netty4框架构建一个客户端,实现与多个不同服务端的稳定连接。内容涵盖Netty的基础概念、客户端配置以及并发连接的管理策略。
摘要由CSDN通过智能技术生成