Nio Client
public class NIOClient {
static int SIZE = 2;
final static int bufferSize = 500 * 1024;
static InetSocketAddress ip = new InetSocketAddress("localhost", 12345);
static CharsetEncoder encoder = Charset.forName("GB2312").newEncoder();
static class Download implements Runnable {
protected int index;
String outfile = null;
public Download(int index) {
this.index = index;
this.outfile = "c:\\" + index + ".rmvb";
}
public void run() {
FileOutputStream fout = null;
// FileChannel fcout = null;
try {
fout = new FileOutputStream(outfile);
// fcout = fout.getChannel();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
long start = System.currentTimeMillis();
// 打开客户端socket管道
SocketChannel client = SocketChannel.open();
// 客户端的管道的通讯模式
client.configureBlocking(false);
// 选择器
Selector selector = Selector.open();
// 往客户端管道上注册感兴趣的连接事件
client.register(selector, SelectionKey.OP_CONNECT);
// 配置IP
client.connect(ip);
// 配置缓存大小
ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
int total = 0;
FOR: for (;;) {
// 阻塞,返回发生感兴趣事件的数量
selector.select();
// 相当于获得感兴趣事件的集合迭代
Iterator<SelectionKey> iter = selector.selectedKeys()
.iterator();
while (iter.hasNext()) {
SelectionKey key = iter.next();
System.out.println("-----Thread " + index
+ "------------------" + key.readyOps());
// 删除这个马上就要被处理的事件
iter.remove();
// 感兴趣的是可连接的事件
if (key.isConnectable()) {
// 获得该事件中的管道对象
SocketChannel channel = (SocketChannel) key.channel();
// 如果该管道对象已经连接好了
if (channel.isConnectionPending())
channel.finishConnect();
// channel.write(encoder.encode(CharBuffer
// .wrap("d://film//" + index + ".mp3")));
// 往管道中写一些块信息
channel.write(encoder.encode(CharBuffer
.wrap("d://film//1-hadoop-1.1.2.tar.gz")));
// 之后为该客户端管道注册新的感兴趣的事件---读操作
channel.register(selector, SelectionKey.OP_READ);
} else if (key.isReadable()) {
// 由事件获得通讯管道
SocketChannel channel = (SocketChannel) key
.channel();
// 从管道中读取数据放到缓存中
int count = channel.read(buffer);
System.out.println("count:" + count);
if (count > 0) {
// 统计读取的字节数目
total += count;
// 这样一来从posistion~limit这段缓存数据是有效,可利用的
// buffer.flip();
buffer.clear();
// 往输出文件中去写了
if (count < bufferSize) {
byte[] overByte = new byte[count];
for (int index = 0; index < count; index++) {
overByte[index] = buffer.get(index);
}
fout.write(overByte);
// System.out.println(":::"
// + new String(buffer.array()));
} else {
fout.write(buffer.array());
// System.out.println(":::"
// + new String(buffer.array()));
}
} else {
// 关闭客户端通道
client.close();
// 退出大循环
break FOR;
}
// ?
// buffer.clear();
}
}
}
// 计算时间
double last = (System.currentTimeMillis() - start) * 1.0 / 1000;
System.out.println("Thread " + index + " downloaded " + total
/ 1024 + "kbytes in " + last + "s.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
long startTime = System.currentTimeMillis();
// 启用线程池
ExecutorService exec = Executors.newFixedThreadPool(SIZE);
for (int index = 1; index <= SIZE; index++) {
exec.execute(new Download(index));
}
exec.shutdown();
long endTime = System.currentTimeMillis();
long timeLong = endTime - startTime;
System.out.println("下载时间:" + timeLong);
}
Nio Client的更多相关文章
- Java nio Client端简单示例
java nio是一种基于Channel.Selector.Buffer的技术,它是一种非阻塞的IO实现方式 以下Client端示例 public class ClientNio { public s ...
- 使用Java Low Level REST Client操作elasticsearch
Java REST客户端有两种风格: Java低级别REST客户端(Java Low Level REST Client,以后都简称低级客户端算了,难得码字):Elasticsearch的官方low- ...
- Java中的NIO基础知识
上一篇介绍了五种NIO模型,本篇将介绍Java中的NIO类库,为学习netty做好铺垫 Java NIO 由3个核心组成,分别是Channels,Buffers,Selectors.本文主要介绍着三个 ...
- NIO网络编程中重复触发读(写)事件
一.前言 公司最近要基于Netty构建一个TCP通讯框架, 因Netty是基于NIO的,为了更好的学习和使用Netty,特意去翻了之前记录的NIO的资料,以及重新实现了一遍NIO的网络通讯,不试不知道 ...
- Java中NIO及基础实现
NIO:同步非阻塞IO 来源:BIO是同步阻塞IO操作,当线程在处理任务时,另一方会阻塞着等待该线程的执行完毕,为了提高效率,,JDK1.4后,引入NIO来提升数据的通讯性能 NIO中采用Reacto ...
- Elasticsearch Java Rest Client简述
ESJavaClient的历史 JavaAPI Client 优势:基于transport进行数据访问,能够使用ES集群内部的性能特性,性能相对好 劣势:client版本需要和es集群版本一致,数据序 ...
- Java的异步HttpClient
上篇提到了高性能处理的关键是异步,而我们当中许多人依旧在使用同步模式的HttpClient访问第三方Web资源,我认为原因之一是:异步的HttpClient诞生较晚,许多人不知道:另外也可能是大多数W ...
- netty-学习笔记
零.socket: http://haohaoxuexi.iteye.com/blog/1979837 一.NIO(1.0)非阻塞 NIO的特点: Buffer,缓冲区 Channel,管道 Sele ...
- httpClient多线程请求
使用httpClient可模拟请求Url获取资源,使用单线程的请求速度上会有一定的限制,参考了Apache给出的例子,自己做了测试实现多线程并发请求,以下代码需要HttpClient 4.2的包,可以 ...
随机推荐
- snort简介以及在Ubuntu下的安装
一.简介 Snort是一套开放源代码的网络入侵预防软件与网络入侵检测软件.Snort使用了以侦测签章(signature-based)与通信协议的侦测方法.Snort是一个免费的IDS(入侵监测系统) ...
- CRM odata方法 js容易出现的错误,大小写区分 Value Id
Id Value 注意大小写,I大写,V大写,typeResults.result[0].yt_category.Value; 否则会报 错,Result.yt_businessunit_terri ...
- Java 基本日期类使用(一)
一.java.util.Date Date表示特定的瞬间,精确到毫秒,其子类有Date.Time.Timestap.默认情况下输出的Date对象为:Mon Oct 13 17:48:47 CST 20 ...
- [转]取代cookie的网站追踪技术:”帆布指纹识别”初探
[前言] 一般情况下,网站或者广告联盟都会非常想要一种技术方式可以在网络上精确定位到每一个个体,这样可以通过收集这些个体的数据,通过分析后更加精准的去推送广告(精准化营销)或其他有针对性的一些活动.C ...
- windows下如何安装配置mysql-5.7-m14-winx64(zip格式的安装)
win7 64位下如何安装配置mysql-5.7.4-m14-winx64 1. mysql-5.7.4-m14-winx64.zip下载 官方网站下载地址:http://dev.mysql.co ...
- 图论测试题(一)第一题:longest
第一题:longest 乌托邦有n个城市,某些城市之间有公路连接.任意两个城市都可以通过公路直接或者间接到达,并且任意两个城市之间有且仅有一条路径(What does this imply? A tr ...
- leetcode Swap Nodes in Pairs python
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = ...
- 常用js表单文本域验证
1.验证是否为正确的邮箱地址 注意:本方法只能验证以@a.b结尾的邮箱地址,对于三级及三级以上的邮箱,比如@iie.ac.cn结尾的会出现错误 function isEmail(o){ var reg ...
- linux杂记(二)主机硬盘规划
linux安装过程中,至少要两个partition,一个是[/],另一个是虚拟内存[swap].但比较不保险. 稍微麻烦点的方式: / /usr:linux操作系统 /home:使用者信息 /var: ...
- Mysql表锁定解决
#查看进程SELECT *FROM information_schema.processlistWHERE USER = 'root' AND state LIKE 'Waiting%';#杀掉进程K ...