一、什么是阻塞和非阻塞?
-
传统的 IO 流都是阻塞式的。也就是说,当一个线程调用 read() 或 write() 时,该线程被阻塞,直到有一些数据被读取或写入,该线程在此期间不 能执行其他任务。因此,在完成网络通信进行 IO 操作时,由于线程会 阻塞,所以服务器端必须为每个客户端都提供一个独立的线程进行处理, 当服务器端需要处理大量客户端时,性能急剧下降。
-
Java NIO 是非阻塞模式的。当线程从某通道进行读写数据时,若没有数 据可用时,该线程可以进行其他任务。线程通常将非阻塞 IO 的空闲时 间用于在其他通道上执行 IO 操作,所以单独的线程可以管理多个输入 和输出通道。因此,NIO 可以让服务器端使用一个或有限几个线程来同 时处理连接到服务器端的所有客户端。
二、NIO中阻塞和非阻塞用法
1. NIO中的阻塞式IO用法
1package com.gf.nio;import org.junit.Test;import java.io.IOException;import java.net.InetSocketAddress;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;import java.nio.channels.ServerSocketChannel;import java.nio.channels.SocketChannel;import java.nio.file.Paths;import java.nio.file.StandardOpenOption;/** 2 * 一、使用 NIO 完成网络通信的三个核心: 3 * 4 * 1. 通道(Channel):负责连接 5 * 6 * java.nio.channels.Channel 接口: 7 * |--SelectableChannel 8 * |--SocketChannel 9 * |--ServerSocketChannel 10 * |--DatagramChannel 11 * 12 * |--Pipe.SinkChannel 13 * |--Pipe.SourceChannel 14 * 15 * 2. 缓冲区(Buffer):负责数据的存取 16 * 17 * 3. 选择器(Selector):是 SelectableChannel 的多路复用器。用于监控 SelectableChannel 的 IO 状况 18 * 19 */public class TestBlockingNIO { 20 21 /** 22 * 客户端 23 */ 24 @Test 25 public void client() throws IOException { 26 //1. 建立网络通道,连接指定服务器端口 27 SocketChannel sChannel = SocketChannel.open(new InetSocketAddress( "127.0.0.1" , 9898 )); 28 //2. 创建客户端本地文件通道 29 FileChannel fileChannel=FileChannel.open( Paths.get("/Users/huanchu/Documents/1.png"), StandardOpenOption.READ); 30 //3. 创建缓冲区 31 ByteBuffer buf = ByteBuffer.allocate(1024); 32 //4. 读取本地文件,发送到服务器 33 while(fileChannel.read(buf) != -1) 34 { 35 buf.flip(); 36 sChannel.write(buf); 37 buf.clear(); 38 } 39 //5.告诉服务端我发送完毕 40 sChannel.shutdownOutput(); 41 42 //接受端反馈 43 int len=0; 44 while((len=sChannel.read(buf))!=-1) 45 { 46 buf.flip(); 47 System.out.println(new String(buf.array(),0,len)); 48 buf.clear(); 49 } 50 51 fileChannel.close(); 52 sChannel.close(); 53 } 54 55 /** 56 * 服务端 57 */ 58 @Test 59 public void server() throws IOException { 60 ServerSocketChannel ssChannel = ServerSocketChannel.open(); 61 FileChannel outChannel = FileChannel.open( Paths.get( "/Users/huanchu/Documents/2.png" ) , StandardOpenOption.WRITE , StandardOpenOption.CREATE ); 62 ssChannel.bind( new InetSocketAddress( 9898 ) ); 63 SocketChannel sChannel = ssChannel.accept(); 64 ByteBuffer buf = ByteBuffer.allocate( 1024 ); 65 66 while (sChannel.read( buf ) != -1) { 67 buf.flip(); 68 outChannel.write( buf ); 69 buf.clear(); 70 } 71 72 //发送反馈给客户端 73 buf.put( "服务端接收数据成功".getBytes() ); 74 buf.flip(); 75 sChannel.write( buf ); 76 77 sChannel.close(); 78 outChannel.close(); 79 80 }}
2. NIO中的非阻塞式IO的使用
SocketChannel
1package com.gf.nio;import org.junit.Test;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.time.Instant;import java.util.Iterator;public class TestNonBlockingNIO { 2 3 /** 4 * 客户端 5 */ 6 @Test 7 public void client() throws IOException { 8 //1. 获取通道 9 SocketChannel sChannel = SocketChannel.open( new InetSocketAddress( "127.0.0.1" ,9898 ) ); 10 11 //2. 切换成非阻塞模式 12 sChannel.configureBlocking( false ); 13 14 //3. 分配指定大小的缓冲区 15 ByteBuffer buf = ByteBuffer.allocate( 1024 ); 16 17 //4. 发送数据给服务端 18 buf.put( Instant.now().toString().getBytes() ); 19 buf.flip(); 20 sChannel.write( buf ); 21 buf.clear(); 22 23 //5. 关闭通道 24 sChannel.close(); 25 26 } 27 28 /** 29 * 服务端 30 */ 31 @Test 32 public void server() throws IOException { 33 //1. 获取通道 34 ServerSocketChannel sChannel = ServerSocketChannel.open(); 35 36 //2. 切换成非阻塞模式 37 sChannel.configureBlocking( false ); 38 39 //3. 绑定连接 40 sChannel.bind( new InetSocketAddress( 9898 ) ); 41 42 //4. 获取选择器 43 Selector selector = Selector.open(); 44 45 //5. 将通道注册到选择器上,并且指定 "监听接收事件" 46 sChannel.register( selector , SelectionKey.OP_ACCEPT ); 47 48 //6. 轮询式的获取选择器上已经 "准备就绪" 的事件 49 while (selector.select() > 0) { 50 //7. 获取当前选择器中所有注册的选择键(已就绪的监听事件) 51 Iterator<SelectionKey> it = selector.selectedKeys().iterator(); 52 53 while (it.hasNext()) { 54 //8. 获取准备就绪的事件 55 SelectionKey sk = it.next(); 56 //9. 判断具体是什么事件准备就绪 57 if (sk.isAcceptable()) { 58 //10. 若 "接受就绪",获取客户端连接 59 SocketChannel ssChannel = sChannel.accept(); 60 61 //11. 切换为非阻塞模式 62 ssChannel.configureBlocking( false ); 63 64 //12. 将该通道注册到选择器上 65 ssChannel.register( selector , SelectionKey.OP_READ); 66 } else if (sk.isReadable()) { 67 //13. 获取当前选择器上“读就绪”状态的通道 68 SocketChannel ssChannel = (SocketChannel) sk.channel(); 69 70 //14. 读取数据 71 ByteBuffer buf = ByteBuffer.allocate(1024); 72 73 int len = 0; 74 while((len = ssChannel.read(buf)) > 0 ){ 75 buf.flip(); 76 System.out.println(new String(buf.array(), 0, len)); 77 buf.clear(); 78 } 79 80 } 81 82 //15. 取消选择键 SelectionKey 83 it.remove(); 84 } 85 86 } 87 88 }}
DatagramChannel
1package com.gf.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 { 2 3 @Test 4 public void send() throws IOException{ 5 DatagramChannel dc = DatagramChannel.open(); 6 7 dc.configureBlocking(false); 8 9 ByteBuffer buf = ByteBuffer.allocate(1024); 10 11 Scanner scan = new Scanner(System.in); 12 13 while(scan.hasNext()){ 14 String str = scan.next(); 15 buf.put((new Date().toString() + ":\n" + str).getBytes()); 16 buf.flip(); 17 dc.send(buf, new InetSocketAddress("127.0.0.1", 9898)); 18 buf.clear(); 19 } 20 21 dc.close(); 22 } 23 24 @Test 25 public void receive() throws IOException{ 26 DatagramChannel dc = DatagramChannel.open(); 27 28 dc.configureBlocking(false); 29 30 dc.bind(new InetSocketAddress(9898)); 31 32 Selector selector = Selector.open(); 33 34 dc.register(selector, SelectionKey.OP_READ); 35 36 while(selector.select() > 0){ 37 Iterator<SelectionKey> it = selector.selectedKeys().iterator(); 38 39 while(it.hasNext()){ 40 SelectionKey sk = it.next(); 41 42 if(sk.isReadable()){ 43 ByteBuffer buf = ByteBuffer.allocate(1024); 44 45 dc.receive(buf); 46 buf.flip(); 47 System.out.println(new String(buf.array(), 0, buf.limit())); 48 buf.clear(); 49 } 50 } 51 52 it.remove(); 53 } 54 }}
本文分享自微信公众号 - 程序员果果(huanchuguofupk_gz)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。