目录
IO模型就是说用什么样的通道进行数据的发送和接收,首先要明确一点:IO是操作系统与其他网络进行数据交互,JDK底层并没有实现IO,而是对操作系统内核函数做的一个封装,IO代码进入底层其实都是native形式的。Java共支持3种网络编程IO模式:BIO,NIO,AIO
一、同步阻塞IO
同步阻塞IO也成为BIO(Blocking IO),是指用户线程发起IO,需要等待系统内核IO操作彻底完成才能返回到用户线程继续执行;在IO操作过程中,用户线程处于阻塞状态;这就是为什么成为阻塞IO的原因.
BIO缺点
- 如果BIO使用单线程接受连接,则会阻塞其他连接,效率较低。如果使用多线程虽然减弱了单线程带来的影响,但当有大并发进来时,会导致服务器线程太多,压力太大而崩溃。
- 多线程也会有线程切换带来的消耗,高并发场景下性能差
示例代码
/**
* BIO代码中连接事件和读写数据事件都是阻塞的,所以这种模式的缺点非常的明显
*
* 1、如果我们连接完成以后,不做读写数据操作会导致线程阻塞,浪费资源
*
* 2、如果没来一个连接我们都需要启动一个线程处理,那么会导致服务器线程太多,压力太大,比如C10K;
*
*/
public class SocketServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(9000);
while (true) {
System.out.println("wait....");
//BIO 阻塞等待链接
Socket accept = serverSocket.accept();
System.out.println("handle request");
new Thread(() -> {
try {
handleRequest(accept);
} catch (Exception e) {
}
}).start();
}
}
private static void handleRequest(Socket clientSocket) throws Exception {
byte[] bytes = new byte[1024];
System.out.println("prepare read.....");
int read = clientSocket.getInputStream().read(bytes);
System.out.println("read end...");
if (read != -1) {
System.out.println("receive client request is " + new String(bytes, 0, read));
}
clientSocket.getOutputStream().write("hello".getBytes());
clientSocket.getOutputStream().flush();
}
}
public class SocketClient {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost", 9000);
socket.getOutputStream().write("hello".getBytes());
socket.getOutputStream().flush();
System.out.println("send request end ..");
byte[] bytes = new byte[1024];
int read = socket.getInputStream().read(bytes);
System.out.println(" response is " + new String(bytes));
socket.close();
}
}
二、同步非阻塞IO
为了解决BIO问题,在JDK1.4引入同步非阻塞IO也称为NIO(Non-Blocking IO),是指用户线程发起IO操作时不会处于阻塞状态。
<