本文主要就NIO入门做个介绍。
1. 同步阻塞I/O:(BIO)
缺点:缺乏弹性,一般直接就是一个服务器端监听,根据来的请求进行创建新的线程进行交互,完成之后销毁线程,存在的问题,有可能由于请求太多,导致服务器宕机,不能向外提供服务。
下面是一个简单地例子:
package com.eric.io;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class HiServer {
private static int port = 12345;
public static void main(String[] args) {
try {
ServerSocket sst = new ServerSocket(port);
Socket socket = new Socket();
/**
* Listens for a connection to be made to this socket and accepts it. The method blocks until a connection is made.
*/
socket = sst.accept();
ServerThread ss = new ServerThread(socket);
ss.run();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static class ServerThread implements Runnable {
private Socket so;
public ServerThread(Socket so) {
this.so = so;
}
public Socket getSo() {
return so;
}
public void setSo(Socket so) {
this.so = so;
}
@Override
public void run() {
BufferedReader br = null;
PrintWriter pw = null;
String requestFromClient = null;
try {
pw = new PrintWriter(so.getOutputStream(), true);
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
br = new BufferedReader(new InputStreamReader(so.getInputStream()));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while (true) {
try {
requestFromClient = br.readLine();
System.out.println("The Request from Client : " + requestFromClient);
pw.println("hello, this is response from server");
} catch (IOException e) {
} finally {
try {
/**
* Closing this socket will also close the socket's
* {@link java.io.InputStream InputStream} and
* {@link java.io.OutputStream OutputStream}.
*
*
If this socket has an associated channel then the channel is closed
* as well.
* **/
so.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
2. 伪异步I/O
采用线程池或者消息队列实现伪异步I/O通信框架,相对于BIO,则线程数是可以控制的.
下面是改造之后的Server.
package com.eric.io;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class HiServer2 {
private static int port = 12345;
private static ExecutorService ex = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), 4, 2,
TimeUnit.SECONDS, new ArrayBlockingQueue<>(1), Executors.defaultThreadFactory(),
new EricSayNoRejectedExecutionHandler());
public static void main(String[] args) {
try {
ServerSocket sst = new ServerSocket(port);
Socket socket = null;
/**
* Listens for a connection to be made to this socket and accepts
* it. The method blocks until a connection is made.
*/
while (true) {
socket = sst.accept();
ServerThread ss = new ServerThread(socket);
ex.execute(ss);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static class ServerThread implements Runnable {
private Socket so;
public ServerThread(Socket so) {
this.so = so;
}
public Socket getSo() {
return so;
}
public void setSo(Socket so) {
this.so = so;
}
@Override
public void run() {
BufferedReader br = null;
PrintWriter pw = null;
String requestFromClient = null;
try {
pw = new PrintWriter(so.getOutputStream(), true);
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
br = new BufferedReader(new InputStreamReader(so.getInputStream()));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
requestFromClient = br.readLine();
System.out.println("The Request from Client : " + requestFromClient);
pw.println("hello, this is response from server");
try {
TimeUnit.SECONDS.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
} finally {
try {
/**
*
* Closing this socket will also close the socket's
* {@link java.io.InputStream InputStream} and
* {@link java.io.OutputStream OutputStream}.
*
*
* If this socket has an associated channel then the channel
* is closed as well.
**/
so.shutdownInput();
so.shutdownOutput();
so.close();
System.out.println(so.isInputShutdown());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private static class EricSayNoRejectedExecutionHandler implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
System.out.println("Sorry , this is no resource for your task");
}
}
}
上面的伪异步依旧无法解决同步IO 根本性问题,因此该方法仅仅就是一定程度上面改善。
存在的问题有如下:如果客户端请求过重,导致服务器端负载太大,大多数的请求将被阻塞,很多情况下面,由于服务器端的性能以及网络带宽因素,引起的服务不稳定同样也会引起服务器崩溃,客户端的请求连接超时等等。
3. NIO(包含AIO)
NIO : none-blocking I/O , 因为是 1.4 版本之后推出的, 所以也叫new I/O, 实际上面 在NIO 2.0 之后提出了新的概念 AIO(asynchronized I/O)
因此引出的相关API 概念(channel, selector等)下面是一些概念介绍 :
(1) 缓冲区buffer
在面向流的I/O中,数据都是直接写入或者读到stream,NIO库中采用的是缓冲区处理,通常是一个字节数组ByteBuffer(CharBuffer等等)
(2) 通道 channel
是一个全双工通道,而流是单向的,需要inputStream 和 outputStream,channel 同时支持读写操作。
(3) 多路复用器 Selector
通过轮询注册在Selector 上面的Channel,通过selectionKey获取Channel 的集合,进行后续的操作,JDK 采用epoll代替传统的select实现,epoll 不受连接句柄数目的影响,用户控件 mmap 同一块内存实现,而且epoll 为每一个 FD指定一个回调函数,将就绪的FD 放入到就绪链表中,因此节省了大量的CPU 时间。