1.简单画的NIO流程图

2.代码实现编程:

Client:

package nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel; /**
*
* @Description:同步非阻塞
* @date 2018年8月4日,下午4:07:30
*/
public class Client { //需要一个Selector
public static void main(String[] args) { //创建连接的地址
InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8765); //声明连接通道
SocketChannel sc = null; //建立缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024); try {
//打开通道
sc = SocketChannel.open();
//进行连接
sc.connect(address); while(true){
//定义一个字节数组,然后使用系统录入功能:
byte[] bytes = new byte[1024];
//读取控制台写入的数据
System.in.read(bytes); //把数据放到缓冲区中
buf.put(bytes);
//对缓冲区进行复位
buf.flip();
//写出数据
sc.write(buf);
//清空缓冲区数据
buf.clear();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(sc != null){
try {
sc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} } }

Server:

package nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator; public class Server implements Runnable{
//1 多路复用器(管理所有的通道)
private Selector seletor;
//2 建立缓冲区
private ByteBuffer readBuf = ByteBuffer.allocate(1024);
//3
private ByteBuffer writeBuf = ByteBuffer.allocate(1024);
public Server(int port){
try {
//1 打开路复用器
this.seletor = Selector.open();
//2 打开服务器通道
ServerSocketChannel ssc = ServerSocketChannel.open();
//3 设置服务器通道为非阻塞模式
ssc.configureBlocking(false);
//4 绑定地址
ssc.bind(new InetSocketAddress(port));
//5 把服务器通道注册到多路复用器上,并且监听阻塞事件
ssc.register(this.seletor, SelectionKey.OP_ACCEPT); System.out.println("Server start, port :" + port); } catch (IOException e) {
e.printStackTrace();
}
} @Override
public void run() {
while(true){
try {
//1 必须要让多路复用器开始监听
this.seletor.select();
//2 返回多路复用器已经选择的结果集
Iterator<SelectionKey> keys = this.seletor.selectedKeys().iterator();
//3 进行遍历
while(keys.hasNext()){
//4 获取一个选择的元素
SelectionKey key = keys.next();
//5 直接从容器中移除就可以了
keys.remove();
//6 如果是有效的
if(key.isValid()){
//7 如果为阻塞状态
if(key.isAcceptable()){
this.accept(key);
}
//8 如果为可读状态
if(key.isReadable()){
this.read(key);
}
//9 写数据
if(key.isWritable()){
this.write(key); //ssc
}
} }
} catch (IOException e) {
e.printStackTrace();
}
}
} private void write(SelectionKey key){
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
try {
ssc.register(this.seletor, SelectionKey.OP_WRITE);
} catch (ClosedChannelException e) {
e.printStackTrace();
}
} private void read(SelectionKey key) {
try {
//1 清空缓冲区旧的数据
this.readBuf.clear();
//2 获取之前注册的socket通道对象
SocketChannel sc = (SocketChannel) key.channel();
//3 读取数据
int count = sc.read(this.readBuf);
//4 如果没有数据
if(count == -1){
key.channel().close();
key.cancel();
return;
}
//5 有数据则进行读取 读取之前需要进行复位方法(把position 和limit进行复位)
this.readBuf.flip();
//6 根据缓冲区的数据长度创建相应大小的byte数组,接收缓冲区的数据
byte[] bytes = new byte[this.readBuf.remaining()];
//7 接收缓冲区数据
this.readBuf.get(bytes);
//8 打印结果
String body = new String(bytes).trim();
System.out.println("Server : " + body); // 9..可以写回给客户端数据 } catch (IOException e) {
e.printStackTrace();
} } private void accept(SelectionKey key) {
try {
//1 获取服务通道
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
//2 执行阻塞方法
SocketChannel sc = ssc.accept();
//3 设置阻塞模式
sc.configureBlocking(false);
//4 注册到多路复用器上,并设置读取标识
sc.register(this.seletor, SelectionKey.OP_READ);
} catch (IOException e) {
e.printStackTrace();
}
} public static void main(String[] args) { new Thread(new Server(8765)).start();;
} }

NIO的学习总结的更多相关文章

  1. NIO模型学习笔记

    NIO模型学习笔记 简介 Non-blocking I/O 或New I/O 自JDK1.4开始使用 应用场景:高并发网络服务器支持 概念理解 模型:对事物共性的抽象 编程模型:对编程共性的抽象 BI ...

  2. Java NIO、NIO.2学习笔记

    相关学习资料 http://www.molotang.com/articles/903.html http://www.ibm.com/developerworks/cn/education/java ...

  3. NIO的学习

    参考 http://wenku.baidu.com/link?url=rq-BEp3Et4JRrE62f2Lv9hq8nT_Gq0XPb65h8OBqTAt-ILfqKmdjIhVEp8bctIdm0 ...

  4. Java NIO 完全学习笔记(转)

    本篇博客依照 Java NIO Tutorial翻译,算是学习 Java NIO 的一个读书笔记.建议大家可以去阅读原文,相信你肯定会受益良多. 1. Java NIO Tutorial Java N ...

  5. Java NIO 核心组件学习笔记

    背景知识 同步.异步.阻塞.非阻塞 首先,这几个概念非常容易搞混淆,但NIO中又有涉及,所以总结一下[1]. 同步:API调用返回时调用者就知道操作的结果如何了(实际读取/写入了多少字节). 异步:相 ...

  6. NIO基础学习——缓冲区

    NIO是对I/O处理的进一步抽象,包含了I/O的基础概念.我是基于网上博友的博客和Ron Hitchens写的<JAVA NIO>来学习的. NIO的三大核心内容:缓冲区,通道,选择器. ...

  7. Java NIO 缓冲区学习笔记

    Buffer其实就是是一个容器对象,它包含一些要写入或者刚读出的数据.在NIO中加入Buffer对象,体现了新库与原I/O的一个重要区别.在面向流的I/O中,您将数据直接写入或者将数据直接读到Stre ...

  8. 【原创】java NIO FileChannel 学习笔记 FileChannel实现分析 即FileChannelImpl分析

    上文已经说了FileChannel是一个抽象类,FileChannelImpl是其实现,接下来介绍FileChannelImpl,参考代码来自OpenJDK7 首先 public class File ...

  9. 【原创】java NIO FileChannel 学习笔记 FileChannel 简介

    java NIO 中FileChannel 的实现类是  FileChannelImpl,FileChannel本身是一个抽象类. 先介绍FileChannel File Channels 是线程安全 ...

  10. java BIO/NIO/AIO 学习

    一.了解Unix网络编程5种I/O模型 1.1.阻塞式I/O模型 阻塞I/O(blocking I/O)模型,进程调用recvfrom,其系统调用直到数据报到达且被拷贝到应用进程的缓冲区中或者发生错误 ...

随机推荐

  1. The linux command 之引用

    [me@linuxbox ~]$ echo this is a test this is a test shell 会对echo进行单词分割(word splitting)去除多余的空白. [me@l ...

  2. CSS W3C统一验证工具

    CssStats 是一个在线的 CSS 代码分析工具  网址是: http://www.cssstats.com/ 如果你想要更全面的,这个神奇,你值得拥有: W3C 统一验证工具: http://v ...

  3. day24 模块

     Python之路,Day12 = Python基础12 模块 本质为py程序 分类: 内置模块 time time.time() ---> 当前时间的时间戳:浮点型 time.localtim ...

  4. (3)mysql表和字段的操作

    创建表 create table name( id int, student ) ); 查看表结构 ****常用**** describe 表名; 修改表名 老表 rename 新表 ALTER TA ...

  5. 阿里云CentOs7上安装Mysql

    前提:虽然yum源上有mysql,但是好像没有mysql-server,所以我们还是选择自己从官网上下载安装 一.新建文件夹,然后下载解压 cd /usr/ #新建mysql文件夹 mkdir mys ...

  6. collections,time,random,os, sys 模块的使用

    主要内容:1. 模块的简单认识2. collections模块3. time时间模块4. random模块5. os模块6. sys模块 一. 模块的简单认识什么是模块. 模块就是我们把装有特定功能的 ...

  7. java中字符数组与字符串之间互相转换的方法

    public static void main(String[] args) { //1.字符数组 转换成 字符串 //(1)直接在构造String时转换 char[] array = new cha ...

  8. Sequence POJ - 3581 后缀数组

    题意: 将一个序列分成非空的三部分,将每部分翻转后组合成一个新的序列, 输出这样操作得到的序列中字典序最小的序列 (保证第一个数是数组中最大的元素) 题解: 把数组当作串串. 因为第一个数最大,所以我 ...

  9. 2019-6-23-天河2-程序-version-GLIBCXX_3.4.21-not-found-解决方法

    title author date CreateTime categories 天河2 程序 version GLIBCXX_3.4.21 not found 解决方法 lindexi 2019-06 ...

  10. 论文翻译——Fast-R-CNN(端到端开篇, End to end)

     快速的区域卷积网络方法(Fast R-CNN)   论文地址:https://arxiv.org/abs/1504.08083 摘要: 本文提出一种基于快速的区域卷积网络方法(Fast R-CNN) ...