- 浏览: 367316 次
- 性别:
- 来自: 杭州
文章分类
最新评论
-
xujishen:
新入职 写道还是没很明白~~这个BigDecimal.ROUN ...
BigDecimal带精度的运算 -
542348257:
数字为long型的时候 好像处理有点问题
【无聊的笔记】将数字转换为中文读法 -
陈小妞:
当你输入100003980的时候在万位会多一个万字
【无聊的笔记】将数字转换为中文读法 -
stranger520:
可能有问题吧,举个例子: pacage1/User.class ...
java读取指定package下的所有class -
springdata_springmvc:
java程序语言学习教程 地址http://www.zuida ...
java学习——mina篇
在前面写的nio学习中是采取的简单的demo,后来在网上看到一个demo,一个用来多线程下载的demo,在这个demo里才会体现nio的高性能之处。充分体现nio的优势。
场景:一个服务端,然后100个客户端同时连接服务端,然后下载一个文件下来。服务端只需要一个连接来处理这些来自客户端的连接。其中对文件的传递采用的是nio中的FileChannel
。很好用的一个东西。
忘记从哪里转过来的代码了。。。
服务端:
import java.io.FileInputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.FileChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.util.Iterator; public class NIOServer { static int BLOCK = 4096; // 处理与客户端的交互 public class HandleClient { protected FileChannel channel; protected ByteBuffer buffer; public HandleClient() throws IOException { this.channel = new FileInputStream(filename).getChannel(); this.buffer = ByteBuffer.allocate(BLOCK); } public ByteBuffer readBlock() { try { buffer.clear(); int count = channel.read(buffer); buffer.flip(); if (count <= 0) return null; } catch (IOException e) { e.printStackTrace(); } return buffer; } public void close() { try { channel.close(); } catch (IOException e) { e.printStackTrace(); } } } protected Selector selector; protected String filename = "d:\\test.jpg"; // a big file protected ByteBuffer clientBuffer = ByteBuffer.allocate(BLOCK); protected CharsetDecoder decoder; public NIOServer(int port) throws IOException { selector = this.getSelector(port); Charset charset = Charset.forName("GB2312"); decoder = charset.newDecoder(); } // 获取Selector protected Selector getSelector(int port) throws IOException { ServerSocketChannel server = ServerSocketChannel.open(); Selector sel = Selector.open(); server.socket().bind(new InetSocketAddress(port)); server.configureBlocking(false); server.register(sel, SelectionKey.OP_ACCEPT); return sel; } // 监听端口 public void listen() { try { for (;;) { selector.select(); Iterator iter = selector.selectedKeys().iterator(); while (iter.hasNext()) { SelectionKey key = (SelectionKey) iter.next(); iter.remove(); handleKey(key); } } } catch (IOException e) { e.printStackTrace(); } } // 处理事件 protected void handleKey(SelectionKey key) throws IOException { if (key.isAcceptable()) { // 接收请求 ServerSocketChannel server = (ServerSocketChannel) key.channel(); SocketChannel channel = server.accept(); channel.configureBlocking(false); channel.register(selector, SelectionKey.OP_READ); } else if (key.isReadable()) { // 读信息 System.out.println("能读"); SocketChannel channel = (SocketChannel) key.channel(); int count = channel.read(clientBuffer); if (count > 0) { clientBuffer.flip(); CharBuffer charBuffer = decoder.decode(clientBuffer); System.out.println("Client >>" + charBuffer.toString()); SelectionKey wKey = channel.register(selector, SelectionKey.OP_WRITE); wKey.attach(new HandleClient()); } else channel.close(); clientBuffer.clear(); } else if (key.isWritable()) { // 写事件 System.out.println("能写"); SocketChannel channel = (SocketChannel) key.channel(); HandleClient handle = (HandleClient) key.attachment(); ByteBuffer block = handle.readBlock(); if (block != null) channel.write(block); else { handle.close(); channel.close(); } } } public static void main(String[] args) { int port = 12345; try { NIOServer server = new NIOServer(port); System.out.println("Listernint on " + port); while (true) { server.listen(); } } catch (IOException e) { e.printStackTrace(); } } }
客户端:
import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.FileChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.util.Iterator; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class NIOClient { static int SIZE = 10; static InetSocketAddress ip = new InetSocketAddress("localhost", 12345); static CharsetEncoder encoder = Charset.forName("GB2312").newEncoder(); static FileChannel[] filechannel = new FileChannel[SIZE]; static class Download implements Runnable { protected int index; public Download(int index) { this.index = index; } public void run() { try { long start = System.currentTimeMillis(); SocketChannel client = SocketChannel.open(); client.configureBlocking(false); Selector selector = Selector.open(); client.register(selector, SelectionKey.OP_CONNECT); client.connect(ip); ByteBuffer buffer = ByteBuffer.allocate(8 * 1024); int total = 0; boolean flag = true; while (flag) { selector.select(); Iterator iter = selector.selectedKeys().iterator(); while (iter.hasNext()) { SelectionKey key = iter.next(); iter.remove(); if (key.isConnectable()) { SocketChannel channel = (SocketChannel) key.channel(); if (channel.isConnectionPending()) channel.finishConnect(); channel.write(encoder.encode(CharBuffer.wrap("Hello from " + index))); channel.register(selector, SelectionKey.OP_READ); } else if (key.isReadable()) { SocketChannel channel = (SocketChannel) key.channel(); int count = channel.read(buffer); if (count > 0) { writeToFile(buffer, index); total += count; buffer.clear(); } else { filechannel[index].close(); client.close(); flag = false; } } } } double last = (System.currentTimeMillis() - start) * 1.0 / 1000; System.out.println("Thread " + index + " downloaded " + total + "bytes in " + last + "s."); } catch (IOException e) { e.printStackTrace(); } } } public static synchronized void writeToFile(ByteBuffer bb, int index) { try { if (filechannel[index] == null) { filechannel[index] = new FileOutputStream(new File("test" + index + ".jpg")).getChannel(); } bb.flip(); filechannel[index].write(bb); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) throws IOException { ExecutorService exec = Executors.newFixedThreadPool(SIZE); for (int index = 0; index < SIZE; index++) { exec.execute(new Download(index)); } exec.shutdown(); } }
发表评论
-
2013年技术愿望目标
2013-01-07 23:25 0一: 读源码 1:jetty 2:webx,spr ... -
jetty的http协议解析
2012-07-31 23:59 0上篇文章讲到:jetty的connection解析到hand ... -
jetty源码阅读之connection解析到handler调用
2012-07-29 21:58 0前言: 想要处理用户发出的http请求,首先得获得连接 ... -
jetty源码阅读之connector
2012-07-29 14:56 0AbstractConnector @Overr ... -
定时执行Timer的源码阅读
2012-02-22 18:51 1665Timer的实现原理: 1:timer简介; ... -
jetty翻译
2011-09-06 23:50 0异步等待 异 ... -
【转】mysql Host is blocked error错误解决方案
2011-08-01 14:40 2838Host is blocked because of ma ... -
java按值传递
2011-06-28 23:13 0来看看代码 packag ... -
【无聊的笔记】将数字转换为中文读法
2011-06-05 15:43 6219将阿拉伯数字的数变成我们常用的中文读法, 比如说: 1 ... -
用mina网络传输使用ObjectSerializationCodecFactory一个小注意点
2011-04-05 18:18 8657背景: 之前的 一篇介绍mina的博客中,提到通过mi ... -
jboss下的war包的context映射配置
2011-02-10 17:19 0一般web容器都可以在 deploy 目录下放多个war包, ... -
maven war plugin 的filter 配置。
2011-02-10 17:14 0具体可以参考,maven的官方配置。 http://m ... -
【why系列】内部类为什么访问外围内需要用final
2011-01-10 13:16 011111111111111 -
java命令行知多少(反正我知道的比较少)
2010-12-29 17:11 3808打开 %java_home%\bin 下面,看一堆的命令 ... -
【why系列】为什么序列化要实现一个空接口Serializable
2010-12-25 22:16 0啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊 -
【why系列】为什么说java是不可变的对象
2010-12-25 22:15 0啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊 package ... -
java线程总结
2010-12-23 15:25 01:java启动一个线程,会为每一个线程,分配一个 ... -
【监控】通过jmx获得系统的gc,内存情况
2010-11-27 21:52 6171通过jmx访问jvm知道的Mbean的一些信息,可以取得系统运 ... -
自动动手写原生态jmx,MbeanInfo,invoke
2010-11-16 22:07 1965使用jmx的东东主要包括下面几个步骤了: 发布j ... -
用spring连接jmx
2010-11-14 18:20 1780接着上一篇 “原生态连接jmx”的例子。 上一篇中,发 ...
相关推荐
NULL 博文链接:https://goon.iteye.com/blog/1775421
NULL 博文链接:https://zheng12tian.iteye.com/blog/1094811
javaNIO学习笔记(csdn)————程序
java 1.4中推出的java.nio(新输入/输出)软件包允许像在其他低级语言——如C语言——中一样进行输入/输出。许多开发者认为这些新功能只能进行非阻塞操作;但是,这些新功能提供许多其他新鲜有趣的特性,它们包括:...
java面试笔试题库java学习比较开发教程互联网公司面试资料大全合集: 100家大公司java笔试题汇总.doc 125条常见的java 面试笔试题大汇总.pdf 2011最新整理java经典代码.doc 25个经典的Spring面试问答.docx 8张图解...
javanio.zip 23.NIO非阻塞通信(Socket/UDP实例、简单聊天系统) javarmi.zip 24.RMI编程(HelloWorld例、计算器实例) javacorba.zip 25.Corba编程(HelloWorld例、计算器实例) 第6部分(4个程序包) java...
Java NIO通信框架在电信领域的实践.docx java.png javaconcurrencyinpractice.pdf JavaEE学习笔记.pdf java_Java_学习笔记.pdf Java_Performance.pdf java代码效率优化.docx Java内存模型的历史变迁.docx Java在游戏...
关于java程序员发展需要学习的路线整理集合 技术 应用技术 计算机基础知识 cpu mem disk net 线程,进程 第三方库 poi Jsoup zxing Gson 数据结构 树 栈 链表 队列 图 操作系统 linux 代码控制...
javanio.zip 23.NIO非阻塞通信(Socket/UDP实例、简单聊天系统) javarmi.zip 24.RMI编程(HelloWorld例、计算器实例) javacorba.zip 25.Corba编程(HelloWorld例、计算器实例) 第6部分(4个程序包) java...
Java中的IO与NIO面试题 Java反射面试题 Java序列化面试题 Java注解面试题 多线程&并发面试题 JVM面试题 Mysql面试题 Redis面试题 Memcached面试题 MongoDB面试题 Spring面试题 Spring Boot面试题 Spring Cloud面试题...
12.4 nio2文件系统 405 12.4.1 api架构概述 405 12.4.2 操作路径 406 12.4.3 属性读取与设定 409 12.4.4 操作文档与目录 412 12.4.5 读取、访问目录 414 12.4.6 过滤、搜索文档 418 12.5 重点复习 ...
javanio.zip 23.NIO非阻塞通信(Socket/UDP实例、简单聊天系统) javarmi.zip 24.RMI编程(HelloWorld例、计算器实例) javacorba.zip 25.Corba编程(HelloWorld例、计算器实例) 第6部分(4个程序包) java...
Java局域网通信——飞鸽传书源代码,大家都知道VB版、VC版还有Delphi版的飞鸽传书软件,但是Java版的确实不多,因此这个Java文件传输实例不可错过,Java网络编程技能的提升很有帮助。 Java聊天程序,包括服务端和...
2、 Java 高级知识 ①线程 ②锁 ③JDK ④反射 ⑤JVM ⑥GC ⑦ IO 和 NIO, AIO 二、 JavaEE 部分 1、 Spring ①IoC 与 Bean 配置、 管理 ②AOP 与事务、 权限控制 ③S2SH 整合开发 ④Spring, JPA 整合 2、 Hibernate...