NIO

一.NIO介绍

 jdk1.4引进的一套新的IO api 

IO操作模式:1.PIO 直接由cpu处理,占有率极高

                      2.DMA 把IO操作控制权交给DMA处理 还是需要占用cpu

                     3.Channel 相当于一个隧道火车,有自己的指令系统是一个协处理器,有很强的独立处理数据输入和输出的能力。

核心部分 Buffer缓冲区                                                                           NIO面向缓冲区 非阻塞IO  有选择器

               Channel 通道                                                                           IO面向流 阻塞IO

               Selector 选择器(轮训器)

Buffer的使用

ByteBuffer  CharBuffer  DoubleBuffer  FloatBuffer   IntBuffer  LongBuffer   ShortBuffer  

  1.使用buffer读写数据遵循以下四个步骤:

a.创建缓冲区,写入数据到buffer

b.调用flip()方法           记录好多数据,要通过flip转换模式

c.从buffer读取数据

d.调用clear(清除所有的数据) 或者compact(只清除已经读过的数据)方法

  2.Buffer中capacity(容量) position(位置) ,limit(限制)

capacity容量,有固定大小值,满了就需要清空

position:当前位置,有数据进入后就移到了下一个可插入的位置 更换模式的时候会被重置为0;

limit写模式下:表示最多能往里面装多少个数据 此时limit等于capacity,

       读模式下:表示最多能读到多少数据写模式的position,

   3.直接缓存区和间接缓存区的区别

间接缓存区:在堆中开辟,易于管理,垃圾回收器可以回收,空间有限,读写的速度很慢

直接缓存区:不在堆中,物理内存中开辟,空间较大,读写速度快但是没有堆的处理器,创建和销毁耗性能。

   4.把数据放到buffer两种方式: a从channer写到buffer b通过buffer的put方法写到buffer。

 5.读取数据: a.从buffer数据读取到channel   b.使用get方法

get():byte abyte=buf.get();可以从指定的position读取

rewind():buffer.rewind()可以将position设置成0,可以读取所有buffer数据,limit不会变,表示能从buffer读取多少数据。

chear():position设回0,limit变成capacity的值,buffer全部清空,未读的消息也会被遗忘。

compact():将所有的未读的数据拷贝到buffer起始处,将position设回最后一个未读元素后面。

mark():标机一个特定的position,之后通过buffer.reset()恢复到position

  6.flip 方法:切换模式写模式转换成读模式,掉完之后将position变为0,limit变到原来position 

  三.Channel

FileChannel     DatagramChannel  SocketChannel  ServerSocketChannel

1.FileChannel 创建方式:a.InputStream,OutPutStream ,RandomAccessFile获取channel

                                         b.jdk1.7以后 使用FileChannel.open()方法

//第一种
RandomAccessFile aFile=new RandomAccessFile("yuanbao.txt","想追风想自由想要一起手牵手,去看海绕世界流浪");
FileChannel inChannel =aFile.getchannel;
//第二种
FileChannel inChannel=FileChannel.open("yuanbao.txt",StandarOpenOption.READ);

2.读取数据:read()

ByteBuffer buf=ByteBuffer.allocate(48);
int byteRead=inchannle.read(buf);

3.向FileChannel写数据 write,FileChannel.write是在循环中调用的,不能保证一次能写完所有的字节,所以需要重复调用write方法,知道没有写入channel的字节。

4.关闭FileChannel  channel.close;

    写入一个文本文件

//1.创建文件输出流
FileOutPutStream fos=new FileOutPutStream("d:\\yuanbao.txt");
//2获取通道 两种方式
FileChannel outchannel=fos.getChannel();
//FileChannel inchannel=FileChannel.open(paths.get("d:\\yuanbao.txt"),StandarOpenOption.READ);
//3.创建缓存区
ByteBuffer buffer=ByteBuffer.allocate(1024);
int len=inchannel.read(buffer);
System.out.println(len);
//4.处理数据
buffer.flip();
String data=new String(buffer.array(),0,len);
System.out.println(data);
inchannel.close;

复制一个图片


import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class Demo1 {
    public static void main(String[] args) throws Exception{
        FileChannel inchannel=FileChannel.open(Paths.get("C:\\Users\\亲元宝\\Pictures\\Camera Roll\\1.jpg"), StandardOpenOption.READ);
        FileChannel inchannel2=FileChannel.open(Paths.get("D:\\1我爱学习\\2.jpg"), StandardOpenOption.WRITE,StandardOpenOption.CREATE);

        ByteBuffer buffer=ByteBuffer.allocate(1024*4);
        int len=0;
        while ((len=inchannel.read(buffer))>0){
            buffer.flip();
            inchannel2.write(buffer);
            buffer.clear();
        }
        inchannel.close();
        inchannel2.close();
        System.out.println("复制完毕");

    }
}

 复制视频大文件:用RandomAcccessFile 复制视频要小于2g 多了需要分多个文件映射

四.selector和非阻塞网络编程

TCP (阻塞式)UDP  

ServerSocketChannel(等同于SeverSocketChannel)  SocketChannel(等同于Socket)实现阻塞式网络编程

Selector

可以类比成一个摩天轮,单个线程处理多个Channel 需要注册

选择器(Selector):Selector选择器类管理着一个被注册的通道集合的信息和它们的就绪状态。通道是和选择器一起被注册的,并且使用选择器来更新通道的就绪状态。

可选择通道(SelectableChannel):SelectableChannel这个抽象类提供了实现通道的可选择性所需要的公共方法。它是所有支持就绪检查的通道类的父类。因为FileChannel类没有继承SelectableChannel因此是不是可选通道,而所有socket通道都是可选择的,SocketChannel和ServerSocketChannel是SelectableChannel的子类。

选择键(SelectionKey):选择键封装了特定的通道与特定的选择器的注册关系。选择键对象被SelectableChannel.register()返回并提供一个表示这种注册关系的标记。选择键包含了两个比特集(以整数的形式进行编码),选择键支持四种操作类型:

a.Connec连接 

b.Accept 接受请求

c.Read读

d.Write

public class Server {
	public static void main(String[] args) throws Exception {
		//1创建ServerSocketChannel
		ServerSocketChannel ssc=ServerSocketChannel.open();
		//2设置为非阻塞式
		ssc.configureBlocking(false);
		//3绑定地址
		ssc.bind(new InetSocketAddress("127.0.0.1",9999));
		//4创建选择器
		Selector selector=Selector.open();
		//5注册选择器
		ssc.register(selector,SelectionKey.OP_ACCEPT);
		while(selector.select()>0){
			Iterator<SelectionKey> it = selector.selectedKeys().iterator();
			while(it.hasNext()){
				SelectionKey selectionKey = it.next();
				if(selectionKey.isAcceptable()){
					SocketChannel socketChannel=ssc.accept();
					socketChannel.configureBlocking(false);
					socketChannel.register(selector, selectionKey.OP_READ);
				}else if(selectionKey.isReadable()){
					//获取SocketChannel
					SocketChannel channel = (SocketChannel) selectionKey.channel();
					//创建缓冲区
					ByteBuffer buffer = ByteBuffer.allocate(1024);
					int len = 0;
					while((len = channel.read(buffer)) > 0 ){
						buffer.flip();
						System.out.println(new String(buffer.array(), 0, len));
						buffer.clear();
					}
                  	  if(len==-1){//客户端已经退出
                          channel.close();
                      }
				}
				it.remove();
			}
		}
	}
}
public class Client {
	public static void main(String[] args) throws Exception{
		//1创建SocketChannel
		SocketChannel sc=SocketChannel.open(new InetSocketAddress("127.0.0.1", 9999));
		//2设置为非阻塞式
		sc.configureBlocking(false);
		//3创建缓冲区
		ByteBuffer buffer=ByteBuffer.allocate(1024);
		Scanner input=new Scanner(System.in);
		while(input.hasNext()){
			String s=input.nextLine();
			buffer.put(s.getBytes());
			buffer.flip();
			sc.write(buffer);
			buffer.clear();
          	 if(s.equals("886")){
				break;
			}
		}
		//4关闭
		sc.close();
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值