BIO: Java 1.4 以前只有之中方式。
bio:阻塞式IO, 一个 socker 连接占用一个 线程。如果 IO 阻塞,会在传输速度限制,这个线程也会一直等待在这里,等待从socker 的 IO 流 中读写数据。
Java 基于 socker 的 连接方式都是 BIO,都是阻塞式的IO。
TCP:
server:
cilent:
原理图:
UDP:
server:
client:
NIO: Java 1.4 以后支持的IO方式
NIO: 非阻塞式的IO, NIO 不再是 传统socker 方式。 一个 IO请求过来,会有一个线程,来处理这个IO请求,但是如果这个IO阻塞,那么这个线程会被处理别的 IO请求的 的事情。如果阻塞的IO的操作完成(完成一个块数据写入缓冲区),那么就会有一个线程分配过来处理这部分数据。
selecter: NIO 不再是 传统socke的概念。 socker 一个 连接,就固定一个 线程来处理,并且这个线程值服务这个 socker。但是 NIO 改变了这种IO 模型, selecter 里面跑着一个独立的线程,这个线程管理 一些渠道( channel , 有点 类似 socker ),如果 某个
渠道的 数据准备好了,那么 selecter 就会分配一个线程来 读写 这个channet 的数据。
buffer: 前面 一直强调 当数据准备好了,什么样才叫数据准备好了? socker 方式的 io 模式是一个 字节 一个字节读写的。 NIO 是通过 一块一块读写的( 一块就是 多个字节 ),但是这个这个 一块数据是 需要 一个临时存放区域的,这就是buffer 。当一个 块 数据满了以后,就分配 线程 来执行这个请求。
channel: 相当于以前的 流的 概念,可以 李杰成一个管道。BIO 一个连接一个线程,并且在socker结束以前一直占用着这个线程。NIO 是一个 也是一个连接一个线程。但是这个线程不会一直 等待这个 连接的IO操作。
例子代码:
server:
client:
BIO 图:
NIO 的 UDP 协议使用:
别的基本一样 只是 渠道使用的 DatagramChannel 。