Java NIO 经典实例代码

NIO和传统IO的区别

1)NIO和传统IO的优势主要体现在服务端进行高并发通信上面,在点对点交换数据的时候不见得比传统IO快

2)NIO在COPY文件的时候相对传统IO来书实现了内存映射

3)NIO是非阻塞的,多路复用的,非阻塞是指一次能读多少就读多少,不像传统IO读不到指定长度内容就不返回,多路复用是指可以多路连接都可以注册在一个selector上,谁有数据进来就处理谁,这样一个线程可以处理很多请求,而传统IO每个客户端都必须为期单独建立一个线程去处理。



NIO SelectionKey中定义的4种事件

  • SelectionKey.OP_ACCEPT —— 接收连接继续事件,表示服务器监听到了客户连接,服务器可以接收这个连接了
  • SelectionKey.OP_CONNECT —— 连接就绪事件,表示客户与服务器的连接已经建立成功
  • SelectionKey.OP_READ —— 读就绪事件,表示通道中已经有了可读的数据,可以执行读操作了(通道目前有数据,可以进行读操作了)
  • SelectionKey.OP_WRITE —— 写就绪件,表示已经可以向通道写数据了(通道目前可以用于写操作)

 这里 注意,下面两种,SelectionKey.OP_READ ,SelectionKey.OP_WRITE ,

1.当向通道中注册SelectionKey.OP_READ事件后,如果客户端有向缓存中write数据,下次轮询时,则会 isReadable()=true;

2.当向通道中注册SelectionKey.OP_WRITE事件后,这时你会发现当前轮询线程中isWritable()一直为ture,如果不设置为其他事件

 



server端代码:

  1. import java.io.IOException;  
  2. import java.net.InetSocketAddress;  
  3. import java.net.ServerSocket;  
  4. import java.nio.ByteBuffer;  
  5. import java.nio.channels.SelectionKey;  
  6. import java.nio.channels.Selector;  
  7. import java.nio.channels.ServerSocketChannel;  
  8. import java.nio.channels.SocketChannel;  
  9. import java.util.Iterator;  
  10. import java.util.Set;  
  11.  
  12. public class NIOServer {  
  13.       
  14.     /*标识数字*/ 
  15.     private  int flag = 0;  
  16.     /*缓冲区大小*/ 
  17.     private  int BLOCK = 4096;  
  18.     /*接受数据缓冲区*/ 
  19.     private  ByteBuffer sendbuffer = ByteBuffer.allocate(BLOCK);  
  20.     /*发送数据缓冲区*/ 
  21.     private  ByteBuffer receivebuffer = ByteBuffer.allocate(BLOCK);  
  22.     private  Selector selector;  
  23.  
  24.     public NIOServer(int port) throws IOException {  
  25.         // 打开服务器套接字通道 
  26.         ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();  
  27.         // 服务器配置为非阻塞 
  28.         serverSocketChannel.configureBlocking(false);  
  29.         // 检索与此通道关联的服务器套接字 
  30.         ServerSocket serverSocket = serverSocketChannel.socket();  
  31.         // 进行服务的绑定 
  32.         serverSocket.bind(new InetSocketAddress(port));  
  33.         // 通过open()方法找到Selector 
  34.         selector = Selector.open();  
  35.         // 注册到selector,等待连接 
  36.         serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);  
  37.         System.out.println("Server Start----8888:");  
  38.     }  
  39.  
  40.  
  41.     // 监听 
  42.     private void listen() throws IOException {  
  43.         while (true) {  
  44.             // 选择一组键,并且相应的通道已经打开 
  45.             selector.select();  
  46.             // 返回此选择器的已选择键集。 
  47.             Set<SelectionKey> selectionKeys = selector.selectedKeys();  
  48.             Iterator<SelectionKey> iterator = selectionKeys.iterator();  
  49.             while (iterator.hasNext()) {          
  50.                 SelectionKey selectionKey = iterator.next();  
  51.                 iterator.remove();  
  52.                 handleKey(selectionKey);  
  53.             }  
  54.         }  
  55.     }  
  56.  
  57.     // 处理请求 
  58.     private void handleKey(SelectionKey selectionKey) throws IOException {  
  59.         // 接受请求 
  60.         ServerSocketChannel server = null;  
  61.         SocketChannel client = null;  
  62.         String receiveText;  
  63.         String sendText;  
  64.         int count=0;  
  65.         // 测试此键的通道是否已准备好接受新的套接字连接。 
  66.         if (selectionKey.isAcceptable()) {  
  67.             // 返回为之创建此键的通道。 
  68.             server = (ServerSocketChannel) selectionKey.channel();  
  69.             // 接受到此通道套接字的连接。 
  70.             // 此方法返回的套接字通道(如果有)将处于阻塞模式。 
  71.             client = server.accept();  
  72.             // 配置为非阻塞 
  73.             client.configureBlocking(false);  
  74.             // 注册到selector,等待连接 
  75.             client.register(selector, SelectionKey.OP_READ);  
  76.         } else if (selectionKey.isReadable()) {  
  77.             // 返回为之创建此键的通道。 
  78.             client = (SocketChannel) selectionKey.channel();  
  79.             //将缓冲区清空以备下次读取 
  80.             receivebuffer.clear();  
  81.             //读取服务器发送来的数据到缓冲区中 
  82.             count = client.read(receivebuffer);   
  83.             if (count > 0) {  
  84.                 receiveText = new String( receivebuffer.array(),0,count);  
  85.                 System.out.println("服务器端接受客户端数据--:"+receiveText);  
  86.                 client.register(selector, SelectionKey.OP_WRITE);  
  87.             }  
  88.         } else if (selectionKey.isWritable()) {  
  89.             //将缓冲区清空以备下次写入 
  90.             sendbuffer.clear();  
  91.             // 返回为之创建此键的通道。 
  92.             client = (SocketChannel) selectionKey.channel();  
  93.             sendText="message from server--" + flag++;  
  94.             //向缓冲区中输入数据 
  95.             sendbuffer.put(sendText.getBytes());  
  96.              //将缓冲区各标志复位,因为向里面put了数据标志被改变要想从中读取数据发向服务器,就要复位 
  97.             sendbuffer.flip();  
  98.             //输出到通道 
  99.             client.write(sendbuffer);  
  100.             System.out.println("服务器端向客户端发送数据--:"+sendText);  
  101.             client.register(selector, SelectionKey.OP_READ);  
  102.         }  
  103.     }  
  104.  
  105.     /** 
  106.      * @param args 
  107.      * @throws IOException 
  108.      */ 
  109.     public static void main(String[] args) throws IOException {  
  110.         // TODO Auto-generated method stub 
  111.         int port = 8888;  
  112.         NIOServer server = new NIOServer(port);  
  113.         server.listen();  
  114.     }  


client端代码:


  1. import java.io.IOException;  
  2. import java.net.InetSocketAddress;  
  3. import java.nio.ByteBuffer;  
  4. import java.nio.channels.SelectionKey;  
  5. import java.nio.channels.Selector;  
  6. import java.nio.channels.SocketChannel;  
  7. import java.util.Iterator;  
  8. import java.util.Set;  
  9.  
  10. public class NIOClient {  
  11.  
  12.     /*标识数字*/ 
  13.     private static int flag = 0;  
  14.     /*缓冲区大小*/ 
  15.     private static int BLOCK = 4096;  
  16.     /*接受数据缓冲区*/ 
  17.     private static ByteBuffer sendbuffer = ByteBuffer.allocate(BLOCK);  
  18.     /*发送数据缓冲区*/ 
  19.     private static ByteBuffer receivebuffer = ByteBuffer.allocate(BLOCK);  
  20.     /*服务器端地址*/ 
  21.     private final static InetSocketAddress SERVER_ADDRESS = new InetSocketAddress(  
  22.             "localhost"1111);  
  23.  
  24.     public static void main(String[] args) throws IOException {  
  25.         // TODO Auto-generated method stub 
  26.         // 打开socket通道 
  27.         SocketChannel socketChannel = SocketChannel.open();  
  28.         // 设置为非阻塞方式 
  29.         socketChannel.configureBlocking(false);  
  30.         // 打开选择器 
  31.         Selector selector = Selector.open();  
  32.         // 注册连接服务端socket动作 
  33.         socketChannel.register(selector, SelectionKey.OP_CONNECT);  
  34.         // 连接 
  35.         socketChannel.connect(SERVER_ADDRESS);  
  36.         // 分配缓冲区大小内存 
  37.           
  38.         Set<SelectionKey> selectionKeys;  
  39.         Iterator<SelectionKey> iterator;  
  40.         SelectionKey selectionKey;  
  41.         SocketChannel client;  
  42.         String receiveText;  
  43.         String sendText;  
  44.         int count=0;  
  45.  
  46.         while (true) {  
  47.             //选择一组键,其相应的通道已为 I/O 操作准备就绪。 
  48.             //此方法执行处于阻塞模式的选择操作。 
  49.             selector.select();  
  50.             //返回此选择器的已选择键集。 
  51.             selectionKeys = selector.selectedKeys();  
  52.             //System.out.println(selectionKeys.size()); 
  53.             iterator = selectionKeys.iterator();  
  54.             while (iterator.hasNext()) {  
  55.                 selectionKey = iterator.next();  
  56.                 if (selectionKey.isConnectable()) {  
  57.                     System.out.println("client connect");  
  58.                     client = (SocketChannel) selectionKey.channel();  
  59.                     // 判断此通道上是否正在进行连接操作。 
  60.                     // 完成套接字通道的连接过程。 
  61.                     if (client.isConnectionPending()) {  
  62.                         client.finishConnect();  
  63.                         System.out.println("完成连接!");  
  64.                         sendbuffer.clear();  
  65.                         sendbuffer.put("Hello,Server".getBytes());  
  66.                         sendbuffer.flip();  
  67.                         client.write(sendbuffer);  
  68.                     }  
  69.                     client.register(selector, SelectionKey.OP_READ);  
  70.                 } else if (selectionKey.isReadable()) {  
  71.                     client = (SocketChannel) selectionKey.channel();  
  72.                     //将缓冲区清空以备下次读取 
  73.                     receivebuffer.clear();  
  74.                     //读取服务器发送来的数据到缓冲区中 
  75.                     count=client.read(receivebuffer);  
  76.                     if(count>0){  
  77.                         receiveText = new String( receivebuffer.array(),0,count);  
  78.                         System.out.println("客户端接受服务器端数据--:"+receiveText);  
  79.                         client.register(selector, SelectionKey.OP_WRITE);  
  80.                     }  
  81.  
  82.                 } else if (selectionKey.isWritable()) {  
  83.                     sendbuffer.clear();  
  84.                     client = (SocketChannel) selectionKey.channel();  
  85.                     sendText = "message from client--" + (flag++);  
  86.                     sendbuffer.put(sendText.getBytes());  
  87.                      //将缓冲区各标志复位,因为向里面put了数据标志被改变要想从中读取数据发向服务器,就要复位 
  88.                     sendbuffer.flip();  
  89.                     client.write(sendbuffer);  
  90.                     System.out.println("客户端向服务器端发送数据--:"+sendText);  
  91.                     client.register(selector, SelectionKey.OP_READ);  
  92.                 }  
  93.             }  
  94.             selectionKeys.clear();  
  95.         }  
  96.     }  

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值