Netty 快速入门系列 - Chapter 3 Netty5.x【第九讲】 - 单客户多Client 重连

MultipleNetty5Client :学习getFirstChannel 通过递归,获取一个可用Channel

 public Channel nextChannel() throws InterruptedException {
     return getFirstChannel(0);

  }

  private Channel getFirstChannel(int tryCount) throws InterruptedException;


private List<Channel> channels; 保存单个客户,多个Client 连接
package com.john.netty.learn.ch05;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;


import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;


public class MultipleNetty5Client {


  private String ip;


  private int port;


  private int count;


  private Bootstrap bootstrap;


  private List<Channel> channels;


  private EventLoopGroup workers = new NioEventLoopGroup();


  private AtomicLong index = new AtomicLong();


  public MultipleNetty5Client(String ip, int port, int count) {


     this.ip = ip;
     this.port = port;
     this.count = count;


     channels = new ArrayList<>(count);
  }


  public void connect() {


     this.bootstrap = new Bootstrap();


     this.bootstrap.group(this.workers);


     bootstrap.channel(NioSocketChannel.class);


     bootstrap.handler(new ChannelInitializer<Channel>() {


       @Override
       protected void initChannel(Channel ch) throws Exception {


          ch.pipeline().addLast(new StringDecoder());
          ch.pipeline().addLast(new StringEncoder());
          ch.pipeline().addLast(new MultClientHandler());
       }
     });


     for (int i = 0; i < this.count; i++) {


       channels.add(bootstrap.connect(this.ip, this.port).channel());


     }


  }


  public Channel nextChannel() throws InterruptedException {


     return getFirstChannel(0);
  }


  private Channel getFirstChannel(int tryCount) throws InterruptedException {


     Channel channel = channels.get((int) Math.abs(index.incrementAndGet() % channels.size()));


     if (!channel.isActive()) {


       reconnect(channel);


       // 重连
       if (tryCount >= channels.size()) {


          throw new IllegalAccessError("No Available Connection Channel!");
       }


       return getFirstChannel(++tryCount);
     }


     return channel;
  }


  private void reconnect(Channel channel) throws InterruptedException {


     synchronized (channel) {


       if (channel.isActive()) {
          return;
       }


       int indexOf = this.channels.indexOf(channel);


       if (indexOf == -1) {
          return;
       }


       channels.set(indexOf, bootstrap.connect(this.ip, this.port).sync().channel());


     }
  }


  public void console() throws Exception {


     BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in, "GBK"));


     while (true) {


       try {


          System.out.println("请输入:");


          String line = bufferedReader.readLine();


          this.send(line);


          if ("quit".equalsIgnoreCase(line)) {


            break;
          }


       } catch (Throwable e) {


       }
     }
  }


  private void send(String message) throws InterruptedException {


     this.nextChannel().writeAndFlush(message);


  }


  public static void main(String[] args) throws Exception {


     MultipleNetty5Client multipleNetty5Client = new MultipleNetty5Client("127.0.0.1", 23, 3);
     multipleNetty5Client.connect();
     multipleNetty5Client.console();
  }
}
 


 MultClientHandler 

package com.john.netty.learn.ch05;


import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;


public class MultClientHandler extends SimpleChannelInboundHandler<String> {


  public MultClientHandler() {
  }


  @Override
  protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {

     System.out.println("Client Read message " + msg);
  }


  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {

     System.out.println("channelActive(ChannelHandlerContext " + ctx + ")");

  }


  @Override
  public void channelInactive(ChannelHandlerContext ctx) throws Exception {

     System.out.println("channelInactive(ChannelHandlerContext " + ctx + ")");

  }


}
所有源码下载 :https://download.csdn.net/download/netcobol/10308871
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值