博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Netty3 - 多连接的客户端示例
阅读量:4041 次
发布时间:2019-05-24

本文共 2450 字,大约阅读时间需要 8 分钟。

Netty 4/5 说明: 目前  http://netty.io/ 发布的最新版本号,但是并没有netty5相关的版本发布了

Netty3 模拟多连接的客户端

 

package xss.netty.netty3.client;import org.jboss.netty.bootstrap.ClientBootstrap;import org.jboss.netty.channel.*;import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;import org.jboss.netty.handler.codec.string.StringDecoder;import org.jboss.netty.handler.codec.string.StringEncoder;import xss.netty.netty3.HelloClientHandler;import java.net.InetSocketAddress;import java.util.Vector;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.atomic.AtomicInteger;/** *  多个连接的客户端 */public class ClientMutliChannel {    //客户端连接服务类    ClientBootstrap clientBootstrap=new ClientBootstrap();    //会话列表//    List
channelList=new ArrayList
(); Vector
channels=new Vector
(); //计数器 private final AtomicInteger index =new AtomicInteger(); /** * 初始化channel 的个数 * @param channelCount */ public void init(int channelCount){ ExecutorService worker = Executors.newCachedThreadPool(); ExecutorService boss = Executors.newCachedThreadPool(); //设置Thread Factory clientBootstrap.setFactory(new NioClientSocketChannelFactory(boss,worker)); //set pipe line factory clientBootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() throws Exception { ChannelPipeline channelPipeline= Channels.pipeline(); channelPipeline.addLast("decoder",new StringDecoder()); channelPipeline.addLast("encoder",new StringEncoder()); channelPipeline.addLast("hello",new HelloClientHandler()); return channelPipeline; } }); //connet to server for(int count=1;count
= channels.size()){// 超出连接连接数的大小 throw new RuntimeException("没有可用的连接"); } return getActiveChannel(count+1);//尝试下一个 } return channel; } /** * 重连 * @param channel */ private void reconnect(Channel channel){ if(channels.indexOf(channel) == -1){ return; } Channel reconnetChannel=clientBootstrap.connect(new InetSocketAddress("127.0.0.1",9999)).getChannel(); channels.set(channels.indexOf(channel),reconnetChannel); }}

 

相关问题: 是不是线程安全的? 粘包/拆包的问题?

后续验证粘包与拆包的问题

 

 

 

 

 

转载地址:http://dwadi.baihongyu.com/

你可能感兴趣的文章
拓扑结构相同子树练习题
查看>>
字符串空格替换练习题
查看>>
最长无重复字符子串练习题
查看>>
获取栈中最小值函数,时间复杂度为O(1)
查看>>
两个栈实现一个队列
查看>>
栈的反转
查看>>
栈的排序,栈顶元素最大.
查看>>
next数组计算.
查看>>
队列的滑动窗口最大值练习题.
查看>>
数组变树练习题
查看>>
打印两个链表的公共值练习题
查看>>
链表逆序问题
查看>>
链表所有为key的节点全部删除
查看>>
判断俩单链表是否相交
查看>>
前中后序遍历二叉树的非递归实现
查看>>
大数相乘,结果在2000位以内
查看>>
二叉树是否对称
查看>>
动态规划-找零钱
查看>>
动态规划-跳台阶
查看>>
动态规划-01背包问题
查看>>