1.BIO,NIO,AIO的区别
BIO(Blocking IO):阻塞式IO。字节流和字符流,输入输出流。它的有点就是代码比较简单、直观;缺点就是 IO 的效率和扩展性很低,
容易成为应用性能瓶颈。
InputStream/OutputStream
Reader/Writer
RandomAccessFile
NIO(NonBlocking IO):非阻塞式IO。Buffer,FileChannel,SocketChannel,selector可以构建多路复用的、同步非阻塞 IO 程序,
同时提供了更接近操作系统底层高性能的数据操作方式。
AIO:(Asynchronous IO)是 NIO 的升级版本,提供了异步非堵塞的 IO 操作方式,异步 IO 是基于事件和回调机制实现的,也就是应用操
作之后会直接返回,不会堵塞在那里,当后台处理完成,操作系统会通知相应的线程进行后续的操作。
2.Buffer:缓冲区,position,limit,capacity.三个变量的含义。
Buffer不能实例化,可以使用allocate()或者directAllocate()分配空间
filp()切换为写模式position为0,limit为数据大小,
clear()清空数据,position切换为0,limit为capacity
compact()压缩数据,把未读的数据放到前面
3.FileChannel:并不可以实现非阻塞传输方式
可以使用FilChannel来实现文件的读写以及复制,要借用缓冲区
可以使用内存映射映射来复制大文件
MappedByteBuffer map = inChannel.map(MapMode.READ_ONLY, 0,inChannel.size());
outChannel.write(map);
4.SocketChannel和ServerSocketChannel网络编程
客户端
1>.获得SocketChannel套接字 SocketChannel cilent=SocketChannel.open(new InetAdress(服务端IP地址,客户端端口号));
2>.创建缓冲区
3>.进行读写操作
4>.关闭资源
服务端
1>.获取ServerSocketChannel套接字ServerSocketChannel ssc=ServereSocketChannel.open();
2>.绑定地址ssc.bind(new InetAddress(服务端IP地址,端口号));
3>.监听SocketChannel channel=ssc.accept();
4>.创建缓冲区
5>.进行读写操作
6>.关闭资源
5.Selector轮询器
服务端
1>.获取ServerSocketChannel套接字ServerSocketChannel ssc=ServereSocketChannel.open();
2>.绑定地址ssc.bind(new InetAddress(服务端IP地址,端口号));
3>.ServerSocketChannel设置为非阻塞;
4>.创建轮询器Selector s=Selector.open();
5>.把ServerSocketChannel放入selector中ssc.register(selector, SelectionKey.OP_ACCEPT);
6>.开始轮询if(Selector.select()>0)
Set selectionKeys = selector.selectedKeys();
Iterator it = selectionKeys.iterator();
if(it.hasNext()){
SelectionKey selectionKey = it.next();
if (selectionKey.isAcceptable()){
SocketChannel socketChannel=ssc.accept();
System.out.println(“已连接”);
//System.out.println(socketChannel.toString());
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
}else if (selectionKey.isReadable()){
ByteBuffer buffer=ByteBuffer.allocate(1024*4);
int length=-1;
SocketChannel channel = (SocketChannel) selectionKey.channel();
while ((length=channel.read(buffer))>0){
buffer.flip();
String data=new String(buffer.array(),0,buffer.limit());
System.out.println(data);
buffer.clear();
}
}
it.remove();//一定要移除
}
...>.关闭资源
客户端
1>.获得SocketChannel套接字 SocketChannel cilent=SocketChannel.open(new InetAdress(服务端IP地址,客户端端口号));
2>.创建缓冲区
3>.进行读写操作
4>.关闭资源
来源:https://blog.csdn.net/summer8244/article/details/100125043