NIO主要原理和适用。
NIO 有一个主要的类Selector,这个类似一个观察者,只要我们把需要探知的socketchannel告诉Selector,我们接着做别的事情,当有 事件发生时,他会通知我们,传回一组SelectionKey,我们读取这些Key,就会获得我们刚刚注册过的socketchannel,然后,我们从 这个Channel中读取数据,放心,包准能够读到,接着我们可以处理这些数据。
Selector内部原理实际是在做一个对所注册的channel的轮询访问,不断的轮询(目前就这一个算法),一旦轮询到一个channel有所注册的事情发生,比如数据来了,他就会站起来报告,交出一把钥匙,让我们通过这把钥匙来读取这个channel的内容。
jdk供的无阻塞I/O(NIO)有效解决了多线程服务器存在的线程开销问题,但在使用上略显得复杂一些。在NIO中使用多线程,主要目的已不是为了应对 每个客户端请求而分配独立的服务线程,而是通过多线程充分使用用多个CPU的处理能力和处理中的等待时间,达到提高服务能力的目的。
这段时间在研究NIO,写篇博客来记住学过的东西。还是从最简单的Hello World开始,
client多线程请求server端,server接收client的名字,并返回Hello! +名字的字符格式给client。当然实际应用并不这么简单,实际可能是访问文件或者数据库获取信息返回给client。非阻塞的NIO有何神秘之处?代码:
1)server端代码
- public class HelloWorldServer {
-
- static int BLOCK = 1024;
- static String name = "";
- protected Selector selector;
- protected ByteBuffer clientBuffer = ByteBuffer.allocate(BLOCK);
- protected CharsetDecoder decoder;
- static CharsetEncoder encoder = Charset.forName("GB2312").newEncoder();
-
- public HelloWorldServer(int port) throws IOException {
- selector = this.getSelector(port);
- Charset charset = Charset.forName("GB2312");
- decoder = charset.newDecoder();
- }
-
-
- 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();
- process(key);
- }
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
-
- protected void process(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()) {
- SocketChannel channel = (SocketChannel) key.channel();
- int count = channel.read(clientBuffer);
- if (count > 0) {
- clientBuffer.flip();
- CharBuffer charBuffer = decoder.decode(clientBuffer);
- name = charBuffer.toString();
-
- SelectionKey sKey = channel.register(selector,
- SelectionKey.OP_WRITE);
- sKey.attach(name);
- } else {
- channel.close();
- }
-
- clientBuffer.clear();
- } else if (key.isWritable()) {
- SocketChannel channel = (SocketChannel) key.channel();
- String name = (String) key.attachment();
-
- ByteBuffer block = encoder.encode(CharBuffer
- .wrap("Hello !" + name));
-
-
- channel.write(block);
-
-
-
- }
- }
-
- public static void main(String[] args) {
- int port = 8888;
- try {
- HelloWorldServer server = new HelloWorldServer(port);
- System.out.println("listening on " + port);
-
- server.listen();
-
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
2)client端代码
- public class HelloWorldClient {
-
- static int SIZE = 10;
- static InetSocketAddress ip = new InetSocketAddress("localhost", 8888);
- static CharsetEncoder encoder = Charset.forName("GB2312").newEncoder();
-
- static class Message implements Runnable {
- protected String name;
- String msg = "";
-
- public Message(String index) {
- this.name = 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;
-
- _FOR: for (;;) {
- selector.select();
- Iterator iter = selector.selectedKeys().iterator();
-
- while (iter.hasNext()) {
- SelectionKey key = (SelectionKey) iter.next();
- iter.remove();
- if (key.isConnectable()) {
- SocketChannel channel = (SocketChannel) key
- .channel();
- if (channel.isConnectionPending())
- channel.finishConnect();
- channel
- .write(encoder
- .encode(CharBuffer.wrap(name)));
-
- channel.register(selector, SelectionKey.OP_READ);
- } else if (key.isReadable()) {
- SocketChannel channel = (SocketChannel) key
- .channel();
- int count = channel.read(buffer);
- if (count > 0) {
- total += count;
- buffer.flip();
-
- while (buffer.remaining() > 0) {
- byte b = buffer.get();
- msg += (char) b;
-
- }
-
- buffer.clear();
- } else {
- client.close();
- break _FOR;
- }
- }
- }
- }
- double last = (System.currentTimeMillis() - start) * 1.0 / 1000;
- System.out.println(msg + "used time :" + last + "s.");
- msg = "";
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-
- public static void main(String[] args) throws IOException {
-
- String names[] = new String[SIZE];
-
- for (int index = 0; index < SIZE; index++) {
- names[index] = "jeff[" + index + "]";
- new Thread(new Message(names[index])).start();
- }
-
- }
- }
分享到:
相关推荐
该资源为Java nio入门的部分简单示例代码,目的是用简单的示例程序,说明nio中的知识点,希望对你的学习有所帮助
Java NIO测试示例
Java nio 超大数据文件 超大数据文件Java nio 超大数据文件 超大数据文件Java nio 超大数据文件 超大数据文件Java nio 超大数据文件 超大数据文件Java nio 超大数据文件 超大数据文件Java nio 超大数据文件 超大数据...
传统的io技术为阻塞的,java新nio是非阻塞的,注册一个op_read事件,注册到selector对象上,当有数据到来时候,selector回通知之前注册事件的对象,进行read处理,看面我看看它是如何使用的
java nio使用示例,介绍了java nio的常用类及使用方法
01-Java NIO-课程简介.mp4 05-Java NIO-Channel-FileChannel详解(一).mp4 06-Java NIO-Channel-FileChannel详解(二).mp4 08-Java NIO-Channel-...23-Java NIO-Selector-示例代码(客户端).mp4 24
JAVA NIO有两种解释:一种叫非阻塞IO(Non-blocking I/O),另一种也叫新的IO(New I/O),其实是同一个概念。它是一种同步非阻塞的I/O模型,也是I/O多路复用的基础,已经被越来越多地应用到大型应用服务器,成为...
04-Java NIO-Channel-FileChannel(介绍和示例).mp4 05-Java NIO-Channel-FileChannel详解(一).mp4 06-Java NIO-Channel-FileChannel详解(二).mp4 07-Java NIO-Channel-Socket通道-概述.mp4 08-Java NIO-Channel-...
Java NIO非阻塞服务器示例.docx
JavaNIO非阻塞服务器示例.pdf
Buffer是数据的容器,在nio中负责数据的存取,java为不同数据类型提供了相对应的缓冲区类型 如:ByteBuffer、CharBuffer、ShortBuffer、IntBuffer、LongBuffer、FloatBuffer 、DoubleBuffer 等。 Buffer的基本使用 ...
带有Java NIO库的样本 简单的TCP / IP服务器,它使用来自客户端的数据并将其写入套接字相应的消息。 相同的回显服务器,但使用Netty框架。 相同的回显服务器,但使用NIO2异步通道。 创建10000个客户端连接的类,...
Java-NIO非阻塞服务器示例.docx
本篇文章主要介绍了Java NIO框架Netty简单使用的示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
java nio 详细说明,想过代码示例,希望能帮助到大家学习
ParallelGit 是为 Git 应用准备的高性能 Java NIO 内存文件系统。ParallelGit 是基于 JGit 构建的, 可以帮助 Java 项目快速的访问 Git 文件。ParallelGit 可以帮助你操作本地 Git仓库,允许你通过 Java 7 nio 文件...
NULL 博文链接:https://shift-alt-ctrl.iteye.com/blog/1840554
socket编程 java代码示例,客户端发送消息,服务端接收
java-port-mapper Java NIO代理示例 那是我第一次使用Java NIO。 该应用程序接受不同端口上的套接字连接,并将它们代理到不同的位置。 现在,我宁愿使用标准的 不愿实现自己的 ,请参见类图:
使用方法见:https://blog.csdn.net/upset_ming/article/details/96491058 1. 修改了前一版本中证书验证的bug,支持JDK8的高版本 2. 支持国密SSL双向认证 3. 将过期的国密证书替换为新证书