JAVA NIO 实例

来源:互联网 发布:手机查看路由器mac地址 编辑:程序博客网 时间:2024/06/06 02:12
最近一直在忙着JAVA NIO的知识,花了一下午的时间,总算写出了一个可以运行的程序,废话少说,上代码!
Java代码 复制代码 收藏代码
  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 staticvoid 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.     } 
Java代码 复制代码 收藏代码
  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 staticint flag = 0
  14.     /*缓冲区大小*/ 
  15.     private staticint BLOCK = 4096
  16.     /*接受数据缓冲区*/ 
  17.     private static ByteBuffer sendbuffer = ByteBuffer.allocate(BLOCK); 
  18.     /*发送数据缓冲区*/ 
  19.     private static ByteBuffer receivebuffer = ByteBuffer.allocate(BLOCK); 
  20.     /*服务器端地址*/ 
  21.     private finalstatic InetSocketAddress SERVER_ADDRESS =new InetSocketAddress( 
  22.             "localhost", 1111); 
  23.  
  24.     public staticvoid 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.     } 
原创粉丝点击