上一篇文章 JAVA NIO编程入门(一)咱们学习了NIO编程的基础知识,并经过一个小demo实战帮助了解NIO编程的channel,buffer等概念。本文会继续学习JAVA NIO编程,并经过一个小示例来帮助理解相关知识,经过本文你将能够学习到html
分散(Scatter)示意图java
从通道填充buffer,必须填充完前一个buffer才会填充后面的buffer,这也意味着不能动态调整每一个buffer的接受大小。编程
汇集(Gather)示意图bash
汇集和分散是相反的形式,从buffer写入数据到通道,只会写入buffer的positon位置到limit位置的内容,也就是意味着能够动态的写入内容到通道中。网络
什么是选择器框架
Selector(选择器)是Java NIO中可以检测多个NIO通道,并可以知道通道是否为诸如读写事件作好准备的组件。这样,一个单独的线程能够管理多个channel,从而管理多个网络链接,提升效率。socket
为何要用选择器分布式
使用了选择器就能够用一个线程管理多个channel,若是多个channel由多个线程管理,线程以前的切换是消耗资源的,而单个线程就避免了线程之间切换的消耗。post
选择器经常使用方法学习
方法名 | 功能 |
---|---|
register(Selector sel, int ops) | 向选择器注册通道,而且能够选择注册指定的事件,目前事件分为4种;1.Connect,2.Accept,3.Read,4.Write,一个通道能够注册多个事件 |
select() | 阻塞到至少有一个通道在你注册的事件上就绪了 |
selectNow() | 不会阻塞,无论什么通道就绪都马上返回 |
select(long timeout) | 和select()同样,除了最长会阻塞timeout毫秒(参数) |
selectedKeys() | 一旦调用了select()方法,而且返回值代表有一个或更多个通道就绪了,而后能够经过调用selector的selectedKeys()方法,访问“已选择键集(selected key set)”中的就绪通道 |
wakeUp() | 能够使调用select()阻塞的对象返回,不阻塞。 |
close() | 用完Selector后调用其close()方法会关闭该Selector,且使注册到该Selector上的全部SelectionKey实例无效。通道自己并不会关闭 |
实战需求说明
编码客户端和服务端,服务端能够接受客户端的请求,并返回一个报文,客户端接受报文并解析输出。
服务端代码
try {
//建立一个服socket并打开
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
//监听绑定8090端口
serverSocketChannel.socket().bind(new InetSocketAddress(8090));
//设置为非阻塞模式
serverSocketChannel.configureBlocking(false);
while(true){
//获取请求链接
SocketChannel socketChannel = serverSocketChannel.accept();
if (socketChannel!=null){
ByteBuffer buf1 = ByteBuffer.allocate(1024);
socketChannel.read(buf1);
buf1.flip();
if(buf1.hasRemaining())
System.out.println(">>>服务端收到数据:"+new String(buf1.array()));
buf1.clear();
//构造返回的报文,分为头部和主体,实际状况能够构造复杂的报文协议,这里只演示,不作特殊设计。
ByteBuffer header = ByteBuffer.allocate(6);
header.put("[head]".getBytes());
ByteBuffer body = ByteBuffer.allocate(1024);
body.put("i am body!".getBytes());
header.flip();
body.flip();
ByteBuffer[] bufferArray = { header, body };
socketChannel.write(bufferArray);
socketChannel.close();
}else{
Thread.sleep(1000);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
复制代码
服务端selector(选择器版本)
try {
//打开选择器
Selector selector = Selector.open();
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(8090));
serverSocketChannel.configureBlocking(false);
//向通道注册选择器,而且注册接受事件
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true) {
//获取已经准备好的通道数量
int readyChannels = selector.selectNow();
//若是没准备好,重试
if (readyChannels == 0) continue;
//获取准备好的通道中的事件集合
Set selectedKeys = selector.selectedKeys();
Iterator keyIterator = selectedKeys.iterator();
while (keyIterator.hasNext()) {
SelectionKey key = (SelectionKey) keyIterator.next();
if (key.isAcceptable()) {
//在本身注册的事件中写业务逻辑,
//我这里注册的是accept事件,
//这部分逻辑和上面非选择器服务端代码同样。
ServerSocketChannel serverSocketChannel1 = (ServerSocketChannel) key.channel();
SocketChannel socketChannel = serverSocketChannel1.accept();
ByteBuffer buf1 = ByteBuffer.allocate(1024);
socketChannel.read(buf1);
buf1.flip();
if (buf1.hasRemaining())
System.out.println(">>>服务端收到数据:" + new String(buf1.array()));
buf1.clear();
ByteBuffer header = ByteBuffer.allocate(6);
header.put("[head]".getBytes());
ByteBuffer body = ByteBuffer.allocate(1024);
body.put("i am body!".getBytes());
header.flip();
body.flip();
ByteBuffer[] bufferArray = {header, body};
socketChannel.write(bufferArray);
socketChannel.close();
} else if (key.isConnectable()) {
} else if (key.isReadable()) {
} else if (key.isWritable()) {
}
//注意每次迭代末尾的keyIterator.remove()调用。
//Selector不会本身从已选择键集中移除SelectionKey实例。必须在处理完通道时本身移除。
//下次该通道变成就绪时,Selector会再次将其放入已选择键集中
keyIterator.remove();
}
}
} catch (IOException e) {
e.printStackTrace();
}
复制代码
客户端代码
try {
//打开socket链接,链接本地8090端口,也就是服务端
SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("127.0.0.1", 8090));
//请求服务端,发送请求
ByteBuffer buf1 = ByteBuffer.allocate(1024);
buf1.put("来着客户端的请求".getBytes());
buf1.flip();
if (buf1.hasRemaining())
socketChannel.write(buf1);
buf1.clear();
//接受服务端的返回,构造接受缓冲区,咱们定义头6个字节为头部,后续其余字节为主体内容。
ByteBuffer header = ByteBuffer.allocate(6);
ByteBuffer body = ByteBuffer.allocate(1024);
ByteBuffer[] bufferArray = { header, body };
socketChannel.read(bufferArray);
header.flip();
body.flip();
if (header.hasRemaining())
System.out.println(">>>客户端接收头部数据:" + new String(header.array()));
if (body.hasRemaining())
System.out.println(">>>客户端接收body数据:" + new String(body.array()));
header.clear();
body.clear();
socketChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
复制代码
运行结果
服务端:
客户端:
这里给出了服务端代码的两个版本,一个是非选择器的版本,一个是选择器的版本。查看最后运行结果,发现客户端根据双方约定的协议格式,正确解析到了头部和body的内容,其实这也是汇集和分散最主要的做用和应用场景,在网络交互中,进行协议报文格式的定义和实现。后续学完NIO编程入门后咱们最后进行总结性的实战,编写一个RPC的demo框架,实现分布式系统的远程调用,有兴趣的同窗能够关注笔者和后续的文章。
《JAVA NIO》