Netty 学习笔记3 客户端
基本使用
- 创建引导类 Bootstrap 对象
// 负责启动客户端以及连接服务端
Bootstrap bootstrap = new Bootstrap();
- 使用 group 方法配置事件循环组
EventLoopGroup workerGroup = new NioEventLoopGroup();
bootstrap.group(workerGroup);
- 设置 channel 类型
// 指定线程模型,驱动着连接的数据读写
bootstrap.channel(NioSocketChannel.class);
// or EpollSocketChannel
// or KQueueSocketChannel
- 定义连接的业务处理逻辑
bootstrap.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) throws Exception {
ChannelPipeline channelPipeline = channel.pipeline();
channelPipeline.addLast(new EchoClientHandler());
}
});
- 设置参数
// 表示连接的超时时间,超过这个时间还是建立不上的话则代表连接失败
bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
// 表示是否开启 TCP 底层心跳机制,true 为开启
bootstrap.option(ChannelOption.SO_KEEPALIVE, true)
// 表示是否开始 Nagle 算法,true 表示关闭,false 表示开启,
// 通俗地说,如果要求高实时性,有数据发送时就马上发送,就设置为 true 关闭,如果需要减少发送次数减少网络交互,就设置为 false 开启
bootstrap.option(ChannelOption.TCP_NODELAY, true)
- 连接服务端
ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 51001).sync();
// 或者这样
bootstrap.remoteAddress(new InetSocketAddress("127.0.0.1", 51001));
//bootstrap.remoteAddress("127.0.0.1", 51001);
ChannelFuture channelFuture = bootstrap.connect().sync();
// 监听关闭事件,阻塞
channelFuture.channel().closeFuture().sync();
失败重连
private static void connect(Bootstrap bootstrap, String host, int port, int retry) {
bootstrap.connect(host, port).addListener(future -> {
if (future.isSuccess()) {
System.out.println("连接成功!");
} else if (retry == 0) {
System.err.println("重试次数已用完,放弃连接!");
} else {
// 第几次重连
int order = (MAX_RETRY - retry) + 1;
// 本次重连的间隔
int delay = 1 << order;
System.out.println("连接失败,第" + order + "次重连……");
bootstrap.config().group().schedule(() -> connect(bootstrap, host, port, retry - 1), delay, TimeUnit.SECONDS);
}
});
}
完整示例
private static final int MAX_RETRY = 5;
public static void main(String[] args) throws InterruptedException {
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(workerGroup);
bootstrap.channel(NioSocketChannel.class);
bootstrap.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel channel) throws Exception {
ChannelPipeline channelPipeline = channel.pipeline();
channelPipeline.addLast(new EchoClientHandler());
}
});
ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 51001).sync();
connect(bootstrap, "127.0.0.1", 51001, MAX_RETRY);
} finally {
workerGroup.shutdownGracefully();
}
}
private static void connect(Bootstrap bootstrap, String host, int port, int retry) {
bootstrap.connect(host, port).addListener(future -> {
if (future.isSuccess()) {
System.out.println("连接成功!");
} else if (retry == 0) {
System.err.println("重试次数已用完,放弃连接!");
} else {
// 第几次重连
int order = (MAX_RETRY - retry) + 1;
// 本次重连的间隔
int delay = 1 << order;
System.out.println("连接失败,第" + order + "次重连……");
bootstrap.config().group().schedule(() -> connect(bootstrap, host, port, retry - 1), delay, TimeUnit.SECONDS);
}
});
}