一、模型说明
1、NIO解决的BIO的核心问题
- 客户端连接的同步阻塞问题
- 读写操作的同步阻塞问题
2、NIO服务端时序图
3、NIO客户端时序图
4、NIO的优点总结
客户端发起的连接是异步的,可以通过多路复用器注册OP_CONNECT等待后续结果,不需要像BIO的客户端那样被同步阻塞
SocketChannel的读写操作都是异步的,如果没有可读写的数据他不会同步等待,直接返回,这样I/O通信线程就可以处理其他链路,而不需要同步等待这个链路的可用
线程模型的优化,由于JDK的Selector在Linux等主流操作系统行通过epoll实现,它没有连接句柄的限制(只受限于操作系统的最大句柄数或者对单个进程的句柄限制),这就意味着Selector线程可以处理成千上万个客户端连接,而且性能不会岁客户端的增加而线性下降。因此它非常适合做高性能、高负载的网络服务器。
5、NIO类库简介
- 缓冲区Buffer:Buffer是一个对象,它包含一些要写入或者读出的数据。在NIO类库中加入Buffer对象,体现出与原I/O的一个重要区别。在面向流的I/O中,可以将数据直接写到或者直接读到Stream对象中。在NIO库中,所有的数据都是用缓冲区处理的,读写都是。缓冲区实质上是一个数组,通常是一个字节数组(ByteBuffer)。但是缓冲区不仅是一个数组,还提供了对数据的结构化访问和维护读写位置的limit等信息。
- 通道Channel:Channel是一个通道,它想自来水管一样,网络数据通过它进行读取和写入,通道和流的不同之处在于通道是双向的,流只是在一个方向上移动(一个流必须是InputStream或者OutputStream的子类),而通道可以用于读、写或者二者同时进行。
- 多路复用器Selector:它是Java NIO编程的基础,多路复用器提供选择已经就绪任务的能力。简单来说,就是Selector会不但轮询注册在其上的Channel,如果某个Channel上发生读或者写事件,这个Channel就处于就绪状态,会被Slector轮询出来,然后通过SelectionKey可以获取就绪Channel的集合,进行后续的I/O操作.
二、代码
1、服务端代码
public class TimeServer {
public static void main(String[] args) {
int port = 8080;
try {
MultiplexerTimerServer server = new MultiplexerTimerServer(port);
new Thread(server,"NIO-MultiplexerTimerServer-001").start();
}catch (Exception e){
e.printStackTrace();
}
}
}
public class MultiplexerTimerServer implements Runnable{
private ServerSocketChannel serverSocketChannel ;
private Selector selector;
private volatile boolean stop;
public MultiplexerTimerServer(int port){
try {
// 初始化多路复用器
selector = Selector.open();
// 初始化serverSocketChannel, 监听端口,设置为非阻塞
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocketChannel.socket().bind(new InetSocketAddress(port), 1024);
// serverSocketChannel注册到多路复用器Selector上,监听OP_ACCEPT事件
SelectionKey key = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("the timer server is started at port : " + port);
}catch (Exception e){
e.printStackTrace();
System.exit(1);
}
}
public void stop(){
this.stop = true;
}
@Override
public void run() {
while (!stop){
try {
selector.select(1000);
Set selectionKeySet = selector.selectedKeys();
Iterator iterator = selectionKeySet.iterator();
SelectionKey key = null;
while (iterator.hasNext()){
key = iterator.next();
iterator.remove();
try {
handleInput(key);
}catch (Exception e){
if (key!=null){
key.cancel();
if (key.channel()!=null){
key.channel().close();
}
}
e.printStackTrace();
}
}
}catch (Exception e){
e.printStackTrace();
}
}
// 多路复用器关闭之后,所有注册到其上的Channel和pipe都会被自动去注册并关闭,所以不需要重复复释放资源
if (selector!=null){
try {
selector.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
private void handleInput(SelectionKey key) throws IOException {
if (key.isValid()){
// 处理新接入的请求, 将accept的SocketChannel配置成非阻塞,同时注册到多路复用器上,监听OP_READ事件
if (key.isAcceptable()){
ServerSocketChannel ss = (ServerSocketChannel) key.channel();
SocketChannel sc = ss.accept();
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_READ);
}
// 处理客户端请求消息(selector中的read事件触发了,则进行处理)
if (key.isReadable()){
// 读取客户端请求消息
SocketChannel sc = (SocketChannel) key.channel();
// 初始化一个capacity为1M的ByteBuffer实例
ByteBuffer readerBuffer = ByteBuffer.allocate(1024);
// 将SocketChannel中的请求消息读取到ByteBuffer区
int readBytes = sc.read(readerBuffer);
// 读取的字节数大于0
if (readBytes > 0){
// 翻转,也就是让flip之后的position到limit这块区域变成之前的0到position这块,翻转就是将一个处于存数据状态的缓冲区变为一个处于准备取数据的状态
readerBuffer.flip();
// 生成一个长度大小为readerBuffer的limit - position大小的字节数组; readerBuffer.remaining()方法返回limit和position之间相对位置差
byte[] bytes = new byte[readerBuffer.remaining()];
// 将readerBuffer对象中存储在字节数组的字节全部读取到bytes中
readerBuffer.get(bytes);
// 转换为字符串
String requestStr = new String(bytes, "UTF-8");
System.out.println("the time server receive msg is : " + requestStr);
// 响应字符串
String responseStr = "now time is : " + System.currentTimeMillis();
// 向客户端响应
doWrite(sc, responseStr);
}else if (readBytes < 0){
// 对端链路关闭
key.cancel();
sc.close();
}else {
// 读取到0字节啥都不做
}
}
}
}
private void doWrite(SocketChannel sc, String responseStr) throws IOException {
if (!StringUtils.isEmpty(responseStr)){
// 字符串转字符数组
byte[] bytes = responseStr.getBytes();
// 初始化一个capacity为1M的ByteBuffer作为写缓冲区
ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
// responseStr内容复制入缓冲区
writeBuffer.put(bytes);
// 翻转
writeBuffer.flip();
// 响应
sc.write(writeBuffer);
System.out.println("the time server response content is : " + responseStr);
}
}
}
2、客户端代码
public class TimeClient {
public static void main(String[] args) {
int port = 8080;
try {
TimeClientHandler timeClientHandler = new TimeClientHandler("127.0.0.1", port);
new Thread(timeClientHandler, "NIO-TimeClientHandler-001").start();
}catch (Exception e){
e.printStackTrace();
}
}
}
public class TimeClientHandler implements Runnable{
private Selector selector;
private SocketChannel sc;
private String host;
private int port;
private volatile boolean isStop;
public TimeClientHandler(String host, int port){
this.host = host;
this.port = port;
try {
selector = Selector.open();
sc = SocketChannel.open();
sc.configureBlocking(false);
}catch (Exception e){
e.printStackTrace();
System.exit(1);
}
}
@Override
public void run() {
// 连接服务端并发送请求
try {
doConnect();
}catch (Exception e){
e.printStackTrace();
System.exit(1);
}
// 读取服务端响应
while (!isStop){
try {
// 每隔1000ms询问一次状态
selector.select(1000);
Set selectionKeySet = selector.selectedKeys();
Iterator it = selectionKeySet.iterator();
SelectionKey key = null;
while (it.hasNext()){
key = it.next();
it.remove();
try {
doInputHandle(key);
}catch (Exception e){
if (key!=null){
key.cancel();
if (key.channel()!=null){
key.channel().close();
}
}
e.printStackTrace();
}
}
}catch (Exception e){
e.printStackTrace();
System.exit(1);
}
}
// 关闭多路复用器
if (selector!=null){
try {
selector.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
private void doConnect() throws IOException {
// 如果直接连接成功,则注册到多路复用器上监听OP_READ事件,发送请求,读取响应;否则,注册到多路复用器上监听OP_COLLECT事件
if (sc.connect(new InetSocketAddress(host, port))){
sc.register(selector, SelectionKey.OP_READ);
doWrite(sc);
}else {
sc.register(selector, SelectionKey.OP_CONNECT);
}
}
private void doWrite(SocketChannel sc) throws IOException {
String requestStr = "what time is now?";
byte[] bytes = requestStr.getBytes();
ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
writeBuffer.put(bytes);
writeBuffer.flip();
sc.write(writeBuffer);
if (!writeBuffer.hasRemaining()){
System.out.println("client send msg succeed");
}
}
private void doInputHandle(SelectionKey key) throws IOException {
if (key.isValid()){
SocketChannel sc = (SocketChannel) key.channel();
// 判断key的通道是否已完成其套接字连接操作,即是否连接成功
if (key.isConnectable()){
if (sc.finishConnect()){
// 完成连接,则发送请求
sc.register(selector, SelectionKey.OP_READ);
doWrite(sc);
}else {
// 连接失败,则退出
System.exit(1);
}
}
// 可读状态才读取响应
if (key.isReadable()){
ByteBuffer readerBuffer = ByteBuffer.allocate(1024);
int readBytes = sc.read(readerBuffer);
if (readBytes>0){
readerBuffer.flip();
byte[] bytes = new byte[readerBuffer.remaining()];
readerBuffer.get(bytes);
String responseStr = new String(bytes, "UTF-8");
System.out.println("now time is : " + responseStr);
this.isStop = true;
}else if (readBytes < 0){
key.cancel();
sc.close();
}else {
}
}
}
}
}
三、运行结果
1、服务端打印结果
the timer server is started at port : 8080
the time server receive msg is : what time is now?
the time server response content is : now time is : 1528527562950
2、客户端打印结果
client send msg succeed
now time is : now time is : 1528527562950