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的更多相关文章

  1. Java nio Client端简单示例

    java nio是一种基于Channel.Selector.Buffer的技术,它是一种非阻塞的IO实现方式 以下Client端示例 public class ClientNio { public s ...

  2. 使用Java Low Level REST Client操作elasticsearch

    Java REST客户端有两种风格: Java低级别REST客户端(Java Low Level REST Client,以后都简称低级客户端算了,难得码字):Elasticsearch的官方low- ...

  3. Java中的NIO基础知识

    上一篇介绍了五种NIO模型,本篇将介绍Java中的NIO类库,为学习netty做好铺垫 Java NIO 由3个核心组成,分别是Channels,Buffers,Selectors.本文主要介绍着三个 ...

  4. NIO网络编程中重复触发读(写)事件

    一.前言 公司最近要基于Netty构建一个TCP通讯框架, 因Netty是基于NIO的,为了更好的学习和使用Netty,特意去翻了之前记录的NIO的资料,以及重新实现了一遍NIO的网络通讯,不试不知道 ...

  5. Java中NIO及基础实现

    NIO:同步非阻塞IO 来源:BIO是同步阻塞IO操作,当线程在处理任务时,另一方会阻塞着等待该线程的执行完毕,为了提高效率,,JDK1.4后,引入NIO来提升数据的通讯性能 NIO中采用Reacto ...

  6. Elasticsearch Java Rest Client简述

    ESJavaClient的历史 JavaAPI Client 优势:基于transport进行数据访问,能够使用ES集群内部的性能特性,性能相对好 劣势:client版本需要和es集群版本一致,数据序 ...

  7. Java的异步HttpClient

    上篇提到了高性能处理的关键是异步,而我们当中许多人依旧在使用同步模式的HttpClient访问第三方Web资源,我认为原因之一是:异步的HttpClient诞生较晚,许多人不知道:另外也可能是大多数W ...

  8. netty-学习笔记

    零.socket: http://haohaoxuexi.iteye.com/blog/1979837 一.NIO(1.0)非阻塞 NIO的特点: Buffer,缓冲区 Channel,管道 Sele ...

  9. httpClient多线程请求

    使用httpClient可模拟请求Url获取资源,使用单线程的请求速度上会有一定的限制,参考了Apache给出的例子,自己做了测试实现多线程并发请求,以下代码需要HttpClient 4.2的包,可以 ...

随机推荐

  1. Android GUI Building Blocks

    说明:此笔记为“Android开发”学习视频的笔记,链接如下:http://open.163.com/movie/2010/1/8/D/M79HE97C3_M79HEQJ8D.html 一, Acti ...

  2. MFC_Office

    添加新项目,MFC应用程序 多个顶级文档,项目类型:Office,其他默认,点击下一步 复合文档支持:容器,右边都勾选,点击下一步 文件拓展名:c,全选,其他默认,点击下一步 数据库支持:无,其他默认 ...

  3. window快捷登陆linux的的设置方式(设置ssh的config配置)

    看看网上其他人如何写的: http://www.xuebuyuan.com/414672.html 文中~的意思是用户目录下的意思: http://blog.csdn.net/newjueqi/art ...

  4. 图片缩放JavaScript原生实现

    function scalImg(aLi){ for(var i=0,l=aLi.length;i<l;i++){ var oImg = new Image(), oLi = aLi[i], i ...

  5. jquery去除字符串首尾空格的方法:$.trim()

    <!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  6. get the first and last collection item in Magento

    $product_collection->getFirstItem() $product_collection->getLastItem()

  7. 循环对XML文档添加Attribute以及移除Element 【转】

    如下面的图片要求,需要把左边的xml文改为右边的文档. 需要添加Attribute,移除Element,但是所添加的Attribute值已经跟被移除的Element值不相同.实现方法可以参考<对 ...

  8. 当PullToRefreshScrollView里面嵌套ListView

    当PullToRefreshScrollView里面嵌套ListView,ListView上面还是有内容的,当下拉刷新的 时候,数据填充完成之后ListView就会往上面滑动,导致ListView上面 ...

  9. jQuery特效 隔行变色

    1.通过使用onmouseover onmouseout方法 2.变色使用background-color(css)属性 3.变色的标签是td(tr仅仅能使用事件,颜色样式不起作用) 第一种方法 使用 ...

  10. C# linq to xml

    XDocument doc = new XDocument( new XDeclaration("1.0", "utf-8", "yes") ...