一、阻塞IO和非阻塞IO
在了解之前可以先了解一下 阻塞非阻塞,异步和同步 https://blog.csdn.net/IPI715718/article/details/89082495
- b传统的 IO 流都是阻塞式的。也就是说,当一个线程调用 read() 或 write() 时,该线程被阻塞,直到有一些数据被读取或写入,该线程在此期间不能执行其他任务。因此,在完成网络通信进行 IO 操作时,由于线程会阻塞,所以服务器端必须为每个客户端都提供一个独立的线程进行处理,当服务器端需要处理大量客户端时,性能急剧下降。
- Java NIO 是非阻塞模式的。当线程从某通道进行读写数据时,若没有数据可用时,该线程可以进行其他任务。线程通常将非阻塞 IO 的空闲时间用于在其他通道上执行 IO 操作,所以单独的线程可以管理多个输入和输出通道。因此,NIO 可以让服务器端使用一个或有限几个线程来同时处理连接到服务器端的所有客户端
IO的阻塞和非阻塞时对于网络通信来讲的,主要体现在非阻塞IO的读,写,接收连接上是不阻塞的,阻塞发生在客户端和服务端。
BIO 阻塞模式 在服务端的等待tcp连接时,如果没有客户端连接,将会阻塞。在读操作时,如果客户端的数据为准备完毕,此时的读操作也是阻塞状态。阻塞的意思就是停下来等待。
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import org.junit.Test;
public class Demo1 {
@Test
public void client() throws Exception {
Socket socket = new Socket("127.0.0.1", 9999);
OutputStream outputStream = socket.getOutputStream();
outputStream.write("bio".getBytes());
socket.close();
outputStream.close();
}
@Test
public void server() throws Exception{
ServerSocket serverSocket = new ServerSocket(9999);
//等待连接 这里会阻塞
Socket socket = serverSocket.accept();
//业务逻辑代码
InputStream inputStream = socket.getInputStream();
byte[] b = new byte[1024];
//读时如果客户端的数据没准备好 也会阻塞
inputStream.read(b);
System.out.println(new String(b));
serverSocket.close();
socket.close();
inputStream.close();
}
}
总结:以上写法只能是单个客户端的连接,当多个客户端连接时就会出现线程之间的阻塞行为,例如A客户端建立的tcp连接到服务器,服务器read() 读取数据,此时A客户端的数据并没有准备好,服务器线程将会在read()操作时阻塞,B客户端无法建立于服务器的连接,因为A线程已经使用了服务器端的当且仅当一次接受连接。
处理多个连接 循环接收连接方式
public void server() throws Exception{
ServerSocket serverSocket = new ServerSocket(9999);
//循环等待连接 这里会阻塞
while(true){
Socket socket = serverSocket.accept();
//处理用户请求
//.........
}
//serverSocket.close();
}
总结:这里使用循环来接受连接,这种方式和单个连接方式基本相近,只是服务器端能循环处理多个请求,但是这种方式也是阻塞的,原因是服务器端是单线程的,每次只能有一个连接被处理,在这个连接被处理的过程非常耗时时,其他的客户端就会长期处于连接时的阻塞状态,直到服务器端正在被处理的连接运行结束,其他的正在阻塞客户端才能与客户端建立连接,但同一时间内也只能是一个。这种方式效率较低,每次只能处理一个请求。
处理多个请求 多线程方式
public void server() throws Exception{
ServerSocket serverSocket = new ServerSocket(9999);
while(true){
//主线程只接受连接
Socket socket = serverSocket.accept();
new Thread(){
public void run() {
//处理用户请求
};
}.start();
}
总结:这种方式是在服务器端主线程只去接受连接,然后将具体的用户请求处理交给子线程来处理, 这时候客户端的每个连接都会被接受,及时是在连接是被阻塞,也只是短时间的,只是可能在服务端主线程的接收连接操作发生阻塞,主线程接收到连接后会立马释放主线程,去继续接受连接,并不会出现服务器处理用户请求而阻塞服务器接收连接。这种方式仍然是阻塞的,这种阻塞体现在多线程的单个线程的业务逻辑中。另外,这中方式比较消耗资源,每个客户端的请求都会在服务器端建立一个线程,当有一万个连接时可以想象,内存会崩溃。
处理多个请求 多线程方式 线程池
@Test
public void server() throws Exception{
ServerSocket serverSocket = new ServerSocket(9999);
while(true) {
Socket socket = serverSocket.accept();
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
cachedThreadPool.execute(new Runnable() {
@Override
public void run() {
//处理用户请求
}
});
}
}
结论:这种方法与多线程不使用线程池相差无几,只是增加了线程复用。
以上BIO的使用可以看出,无论怎么改进,在单个线程上都是阻塞的(即使是多线程模式),这时候我们就要考虑了,有没有一种方式是,用一个线程去处理多个请求并且,服务器端不需要去阻塞的去等待客户端的连接,而是当连接来的时候有一个信号去告诉线程当前有用户的请求了,你去处理请求。这时候NIO的选择器就派上用场了。
二、选择器(selector)
选择器(Selector) 是 SelectableChannle 对象的多路复用器,Selector 可以同时监控多个 SelectableChannel 的 IO 状况,也就是说,利用 Selector 可使一个单独的线程管理多个 Channel。Selector 是非阻塞 IO 的核心。
SelectableChannle 的结构如下图:
选择器(Selector)的使用:
1. 创建 Selector :通过调用 Selector.open() 方法创建一个 Selector。
Selector selector = Selector.open();
2. 向Selector中注册通道:SelectableChannel.register(Selector sel, int ops)。
//创建ServerSocketChannel
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
//调整此通道的阻塞模式为非阻塞
serverSocketChannel.configureBlocking(false);
//创建选择器
Selector selector = Selector.open();
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
这里注意只要是向选择器中注册通道,该通道一定是非阻塞的,否则会抛IllegalBlockingModeException异常。 看一下方法的源码:if (blocking)
throw new IllegalBlockingModeException();
public final SelectionKey register(Selector sel, int ops,
Object att)
throws ClosedChannelException
{
synchronized (regLock) {
if (!isOpen())
throw new ClosedChannelException();
if ((ops & ~validOps()) != 0)
throw new IllegalArgumentException();
if (blocking)
throw new IllegalBlockingModeException();
SelectionKey k = findKey(sel);
if (k != null) {
k.interestOps(ops);
k.attach(att);
}
if (k == null) {
// New registration
synchronized (keyLock) {
if (!isOpen())
throw new ClosedChannelException();
k = ((AbstractSelector)sel).register(this, ops, att);
addKey(k);
}
}
return k;
}
}
SelectionKey
当调用 register(Selector sel, int ops) 将通道注册选择器时,选择器对通道的监听事件,需要通过第二个参数 ops 指定。
可以监听的事件类型(可使用 SelectionKey 的四个常量表示):
- 读 : SelectionKey.OP_READ (1)
- 写 : SelectionKey.OP_WRITE (4)
- 连接 : SelectionKey.OP_CONNECT (8)
- 接收 : SelectionKey.OP_ACCEPT (16)
若注册时不止监听一个事件,则可以使用“位或”操作符连接。
SelectionKey:表示 SelectableChannel 和 Selector 之间的注册关系。每次向选择器注册通道时就会选择一个事件(选择键)。选择键包含两个表示为整数值的操作集。操作集的每一位都表示该键的通道所支持的一类可选择操作。
Selector常用的方法
测试:
package com.atguigu.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Iterator;
import java.util.Scanner;
import org.junit.Test;
/*
* 一、使用 NIO 完成网络通信的三个核心:
*
* 1. 通道(Channel):负责连接
*
* java.nio.channels.Channel 接口:
* |--SelectableChannel
* |--SocketChannel
* |--ServerSocketChannel
* |--DatagramChannel
*
* |--Pipe.SinkChannel
* |--Pipe.SourceChannel
*
* 2. 缓冲区(Buffer):负责数据的存取
*
* 3. 选择器(Selector):是 SelectableChannel 的多路复用器。用于监控 SelectableChannel 的 IO 状况
*
*/
public class TestNonBlockingNIO {
//客户端
@Test
public void client() throws IOException{
//1. 获取通道
SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));
//2. 切换非阻塞模式
sChannel.configureBlocking(false);
//3. 分配指定大小的缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
//4. 发送数据给服务端
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
String str = scan.next();
buf.put((new Date().toString() + "\n" + str).getBytes());
buf.flip();
sChannel.write(buf);
buf.clear();
}
//5. 关闭通道
sChannel.close();
}
//服务端
@Test
public void server() throws IOException{
//1. 获取通道
ServerSocketChannel ssChannel = ServerSocketChannel.open();
//2. 切换非阻塞模式
ssChannel.configureBlocking(false);
//3. 绑定连接
ssChannel.bind(new InetSocketAddress(9898));
//4. 获取选择器
Selector selector = Selector.open();
//5. 将通道注册到选择器上, 并且指定“监听接收事件”
ssChannel.register(selector, SelectionKey.OP_ACCEPT);
//6. 轮询式的获取选择器上已经“准备就绪”的事件
while(selector.select() > 0){
//7. 获取当前选择器中所有注册的“选择键(已就绪的监听事件)”
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while(it.hasNext()){
//8. 获取准备“就绪”的是事件
SelectionKey sk = it.next();
//9. 判断具体是什么事件准备就绪
if(sk.isAcceptable()){
//10. 若“接收就绪”,获取客户端连接
SocketChannel sChannel = ssChannel.accept();
//11. 切换非阻塞模式
sChannel.configureBlocking(false);
//12. 将该通道注册到选择器上
sChannel.register(selector, SelectionKey.OP_READ);
}else if(sk.isReadable()){
//13. 获取当前选择器上“读就绪”状态的通道
SocketChannel sChannel = (SocketChannel) sk.channel();
//14. 读取数据
ByteBuffer buf = ByteBuffer.allocate(1024);
int len = 0;
while((len = sChannel.read(buf)) > 0 ){
buf.flip();
System.out.println(new String(buf.array(), 0, len));
buf.clear();
}
}
//15. 取消选择键 SelectionKey
it.remove();
}
}
}
}
SocketChannel
Java NIO中的SocketChannel是一个连接到TCP网络套接字的通道。
操作步骤:
1 打开 SocketChannel
2 读写数据
3 关闭 SocketChannel
SocketChannel
Java NIO中的 ServerSocketChannel 是一个可以监听新进来的TCP连接的通道,就像标准IO中
的ServerSocket一样。
DatagramChannel
Java NIO中的DatagramChannel是一个能收发UDP包的通道。
操作步骤:
1 打开 DatagramChannel
2 接收/发送数据
测试:
package com.atguigu.nio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Date;
import java.util.Iterator;
import java.util.Scanner;
import org.junit.Test;
public class TestNonBlockingNIO2 {
@Test
public void send() throws IOException{
DatagramChannel dc = DatagramChannel.open();
dc.configureBlocking(false);
ByteBuffer buf = ByteBuffer.allocate(1024);
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
String str = scan.next();
buf.put((new Date().toString() + ":\n" + str).getBytes());
buf.flip();
dc.send(buf, new InetSocketAddress("127.0.0.1", 9898));
buf.clear();
}
dc.close();
}
@Test
public void receive() throws IOException{
DatagramChannel dc = DatagramChannel.open();
dc.configureBlocking(false);
dc.bind(new InetSocketAddress(9898));
Selector selector = Selector.open();
dc.register(selector, SelectionKey.OP_READ);
while(selector.select() > 0){
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while(it.hasNext()){
SelectionKey sk = it.next();
if(sk.isReadable()){
ByteBuffer buf = ByteBuffer.allocate(1024);
dc.receive(buf);
buf.flip();
System.out.println(new String(buf.array(), 0, buf.limit()));
buf.clear();
}
}
it.remove();
}
}
}
管道 (Pipe)
Java NIO 管道是2个线程之间的单向数据连接。Pipe有一个source通道和一个sink通道。数据会被写到sink通道,从source通道读取。
测试:
package com.atguigu.nio;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
import org.junit.Test;
public class TestPipe {
@Test
public void test1() throws IOException{
//1. 获取管道
Pipe pipe = Pipe.open();
//2. 将缓冲区中的数据写入管道
ByteBuffer buf = ByteBuffer.allocate(1024);
Pipe.SinkChannel sinkChannel = pipe.sink();
buf.put("通过单向管道发送数据".getBytes());
buf.flip();
sinkChannel.write(buf);
//3. 读取缓冲区中的数据
Pipe.SourceChannel sourceChannel = pipe.source();
buf.flip();
int len = sourceChannel.read(buf);
System.out.println(new String(buf.array(), 0, len));
sourceChannel.close();
sinkChannel.close();
}
}