自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Java NIO 經(jīng)典實(shí)例代碼

開發(fā) 后端
最近一直在忙著JAVA NIO的知識,花了一下午的時(shí)間,總算寫出了一個(gè)可以運(yùn)行的程序,廢話少說,上代碼!

最近一直在忙著JAVA NIO的知識,花了一下午的時(shí)間,總算寫出了一個(gè)可以運(yùn)行的程序,廢話少說,上代碼!

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.     /*標(biāo)識數(shù)字*/ 
  15.     private  int flag = 0;  
  16.     /*緩沖區(qū)大小*/ 
  17.     private  int BLOCK = 4096;  
  18.     /*接受數(shù)據(jù)緩沖區(qū)*/ 
  19.     private  ByteBuffer sendbuffer = ByteBuffer.allocate(BLOCK);  
  20.     /*發(fā)送數(shù)據(jù)緩沖區(qū)*/ 
  21.     private  ByteBuffer receivebuffer = ByteBuffer.allocate(BLOCK);  
  22.     private  Selector selector;  
  23.  
  24.     public NIOServer(int port) throws IOException {  
  25.         // 打開服務(wù)器套接字通道  
  26.         ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();  
  27.         // 服務(wù)器配置為非阻塞  
  28.         serverSocketChannel.configureBlocking(false);  
  29.         // 檢索與此通道關(guān)聯(lián)的服務(wù)器套接字  
  30.         ServerSocket serverSocket = serverSocketChannel.socket();  
  31.         // 進(jìn)行服務(wù)的綁定  
  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.     // 監(jiān)聽  
  42.     private void listen() throws IOException {  
  43.         while (true) {  
  44.             // 選擇一組鍵,并且相應(yīng)的通道已經(jīng)打開  
  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.         // 測試此鍵的通道是否已準(zhǔn)備好接受新的套接字連接。  
  66.         if (selectionKey.isAcceptable()) {  
  67.             // 返回為之創(chuàng)建此鍵的通道。  
  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.             // 返回為之創(chuàng)建此鍵的通道。  
  78.             client = (SocketChannel) selectionKey.channel();  
  79.             //將緩沖區(qū)清空以備下次讀取  
  80.             receivebuffer.clear();  
  81.             //讀取服務(wù)器發(fā)送來的數(shù)據(jù)到緩沖區(qū)中  
  82.             count = client.read(receivebuffer);   
  83.             if (count > 0) {  
  84.                 receiveText = new String( receivebuffer.array(),0,count);  
  85.                 System.out.println("服務(wù)器端接受客戶端數(shù)據(jù)--:"+receiveText);  
  86.                 client.register(selector, SelectionKey.OP_WRITE);  
  87.             }  
  88.         } else if (selectionKey.isWritable()) {  
  89.             //將緩沖區(qū)清空以備下次寫入  
  90.             sendbuffer.clear();  
  91.             // 返回為之創(chuàng)建此鍵的通道。  
  92.             client = (SocketChannel) selectionKey.channel();  
  93.             sendText="message from server--" + flag++;  
  94.             //向緩沖區(qū)中輸入數(shù)據(jù)  
  95.             sendbuffer.put(sendText.getBytes());  
  96.              //將緩沖區(qū)各標(biāo)志復(fù)位,因?yàn)橄蚶锩鎝ut了數(shù)據(jù)標(biāo)志被改變要想從中讀取數(shù)據(jù)發(fā)向服務(wù)器,就要復(fù)位  
  97.             sendbuffer.flip();  
  98.             //輸出到通道  
  99.             client.write(sendbuffer);  
  100.             System.out.println("服務(wù)器端向客戶端發(fā)送數(shù)據(jù)--:"+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.     }  

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.     /*標(biāo)識數(shù)字*/ 
  13.     private static int flag = 0;  
  14.     /*緩沖區(qū)大小*/ 
  15.     private static int BLOCK = 4096;  
  16.     /*接受數(shù)據(jù)緩沖區(qū)*/ 
  17.     private static ByteBuffer sendbuffer = ByteBuffer.allocate(BLOCK);  
  18.     /*發(fā)送數(shù)據(jù)緩沖區(qū)*/ 
  19.     private static ByteBuffer receivebuffer = ByteBuffer.allocate(BLOCK);  
  20.     /*服務(wù)器端地址*/ 
  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.         // 設(shè)置為非阻塞方式  
  29.         socketChannel.configureBlocking(false);  
  30.         // 打開選擇器  
  31.         Selector selector = Selector.open();  
  32.         // 注冊連接服務(wù)端socket動(dòng)作  
  33.         socketChannel.register(selector, SelectionKey.OP_CONNECT);  
  34.         // 連接  
  35.         socketChannel.connect(SERVER_ADDRESS);  
  36.         // 分配緩沖區(qū)大小內(nèi)存  
  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.             //選擇一組鍵,其相應(yīng)的通道已為 I/O 操作準(zhǔn)備就緒。  
  48.             //此方法執(zhí)行處于阻塞模式的選擇操作。  
  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.                     // 判斷此通道上是否正在進(jìn)行連接操作。  
  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.                     //將緩沖區(qū)清空以備下次讀取  
  73.                     receivebuffer.clear();  
  74.                     //讀取服務(wù)器發(fā)送來的數(shù)據(jù)到緩沖區(qū)中  
  75.                     count=client.read(receivebuffer);  
  76.                     if(count>0){  
  77.                         receiveText = new String( receivebuffer.array(),0,count);  
  78.                         System.out.println("客戶端接受服務(wù)器端數(shù)據(jù)--:"+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.                      //將緩沖區(qū)各標(biāo)志復(fù)位,因?yàn)橄蚶锩鎝ut了數(shù)據(jù)標(biāo)志被改變要想從中讀取數(shù)據(jù)發(fā)向服務(wù)器,就要復(fù)位  
  88.                     sendbuffer.flip();  
  89.                     client.write(sendbuffer);  
  90.                     System.out.println("客戶端向服務(wù)器端發(fā)送數(shù)據(jù)--:"+sendText);  
  91.                     client.register(selector, SelectionKey.OP_READ);  
  92.                 }  
  93.             }  
  94.             selectionKeys.clear();  
  95.         }  
  96.     }  

個(gè)人感覺,JAVA NIO的操作時(shí)麻煩了不少,但是無疑這樣做效率會(huì)得到很大的提升。

原文鏈接:http://xm-king.iteye.com/blog/766330

 【編輯推薦】

  1. Java NIO 經(jīng)典實(shí)例代碼
  2. Java NIO性能測試
  3. Java數(shù)據(jù)緩存實(shí)現(xiàn)的核心機(jī)制
  4. NIO需要了解的一些概念
  5. Java NIO TCP編程
責(zé)任編輯:林師授 來源: xm_king的博客
相關(guān)推薦

2011-12-15 11:19:08

JavaNIO

2011-12-07 14:41:51

JavaNIO

2011-12-15 11:11:51

JavaNIO

2011-12-15 10:19:55

JavaNIO

2011-12-15 11:03:21

JavaNIO

2010-08-26 21:34:19

2010-03-03 14:05:36

Python實(shí)例應(yīng)用

2012-04-11 15:41:48

JavaNIO

2010-03-19 15:02:50

Java Socket

2010-09-13 14:47:58

2010-09-13 15:06:36

2009-02-06 13:19:02

JSP配置Tomcat

2010-03-02 13:43:01

WCF事務(wù)演示

2011-07-20 12:55:17

SQLite數(shù)據(jù)庫插入數(shù)據(jù)

2011-12-15 09:55:47

javanio

2011-12-07 14:57:44

JavaNIO

2011-12-15 09:40:06

Javanio

2010-09-13 15:14:03

2010-09-13 14:57:29

2015-01-16 09:22:54

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號