閱讀64 返回首頁    go 京東網上商城


在Java中使用NIO進行網絡編程

在JDK中,有一個非常有意思的庫:NIO(New I/O)。這個庫中有3個重要的類,分別是java.nio.channels中Selector和Channel,以及java.nio中的Buffer。

本篇文章我們首先了解一下為什麼需要NIO來進行網絡編程,然後看看一步一步來講解如何在網絡編程中使用NIO。

為什麼需要NIO

使用Java編寫過Socket程序的同學一定都知道Socket和SocketServer。當調用某個調用的時候,調用的地方就會阻塞,等待響應。這種方式對於小規模的程序非常方便,但是對於大型的程序就有點力不從心了,當有大量的連接的時候,我們可以為每一個連接建立一個線程來操作。但是這種做法帶來的缺陷也是顯而易見的:

  1. 硬件能夠支持大量的並發。

  2. 並發的數量始終有一個上限。

  3. 各個線程之間的優先級不好控製。

  4. 各個Client之間的交互與同步困難。

我們也可以使用一個線程來處理所有的請求,使用不阻塞的IO,輪詢查詢所有的Client。這種做法同樣也有缺陷:無法迅速響應Client端,同時會消耗大量輪詢查詢的時間。

所以,我們需要一種poll的模式來處理這種情況,從大量的網絡連接中找出來真正需要服務的Client。這正是NIO誕生的原因:提供一種Poll的模式,在所有的Client中找到需要服務的Client。

回到我們剛剛說到的3個最最重要的Class:java.nio.channels中Selector和Channel,以及java.nio中的Buffer。

Channel代表一個可以被用於Poll操作的對象(可以是文件流也可以使網絡流),Channel能夠被注冊到一個Selector中。通過調用Selector的select方法可以從所有的Channel中找到需要服務的實例(Accept,read ..)。Buffer對象提供讀寫數據的緩存。相對於我們熟悉的Stream對象,Buffer提供更好的性能以及更好的編程透明性(人為控製緩存的大小以及具體的操作)。

配合Buffer使用Channel

與傳統模式的編程不用,Channel不使用Stream,而是Buffer。我們來實現一個簡單的非阻塞Echo Client:

 

[java] view plaincopy
  1. package com.cnblogs.gpcuster;  
  2. import java.net.InetSocketAddress;  
  3. import java.net.SocketException;  
  4. import java.nio.ByteBuffer;  
  5. import java.nio.channels.SocketChannel;  
  6. public class TCPEchoClientNonblocking {  
  7.     public static void main(String args[]) throws Exception {  
  8.         if ((args.length < 2) || (args.length > 3))// Testforcorrect#ofargs  
  9.             throw new IllegalArgumentException(  
  10.                     "Parameter(s): <Server> <Word> [<Port>]");  
  11.         String server = args[0];// ServernameorIPaddress  
  12.         // ConvertinputStringtobytesusingthedefaultcharset  
  13.         byte[] argument = args[1].getBytes();  
  14.         int servPort = (args.length == 3) ? Integer.parseInt(args[2]) : 7;  
  15.         // Createchannelandsettononblocking  
  16.         SocketChannel clntChan = SocketChannel.open();  
  17.         clntChan.configureBlocking(false);  
  18.         // Initiateconnectiontoserverandrepeatedlypolluntilcomplete  
  19.         if (!clntChan.connect(new InetSocketAddress(server, servPort))) {  
  20.             while (!clntChan.finishConnect()) {  
  21.                 System.out.print(".");// Dosomethingelse  
  22.             }  
  23.         }  
  24.         ByteBuffer writeBuf = ByteBuffer.wrap(argument);  
  25.         ByteBuffer readBuf = ByteBuffer.allocate(argument.length);  
  26.         int totalBytesRcvd = 0;// Totalbytesreceivedsofar  
  27.         int bytesRcvd;// Bytesreceivedinlastread  
  28.         while (totalBytesRcvd < argument.length) {  
  29.             if (writeBuf.hasRemaining()) {  
  30.                 clntChan.write(writeBuf);  
  31.             }  
  32.             if ((bytesRcvd = clntChan.read(readBuf)) == -1) {  
  33.                 throw new SocketException("Connection closed prematurely");  
  34.             }  
  35.             totalBytesRcvd += bytesRcvd;  
  36.             System.out.print(".");// Dosomethingelse  
  37.         }  
  38.         System.out.println("Received:" + // converttoStringperdefaultcharset  
  39.                 new String(readBuf.array(), 0, totalBytesRcvd));  
  40.         clntChan.close();  
  41.     }  
  42. }  

這段代碼使用ByteBuffer來保存讀寫的數據。通過clntChan.configureBlocking(false
); 設置後,其中的connect,read,write操作都不回阻塞,而是立刻放回結果。

使用Selector

Selector的可以從所有的被注冊到自己Channel中找到需要服務的實例。

我們來實現Echo Server。

首先,定義一個接口:

 

[java] view plaincopy
  1. package com.cnblogs.gpcuster;  
  2. import java.nio.channels.SelectionKey;  
  3. import java.io.IOException;  
  4. public interface TCPProtocol {  
  5.     void handleAccept(SelectionKey key) throws IOException;  
  6.     void handleRead(SelectionKey key) throws IOException;  
  7.     void handleWrite(SelectionKey key) throws IOException;  
  8. }  

 我們通過listnChannel.register(selector, SelectionKey.OP_ACCEPT); 注冊了一個我們感興趣的事件,然後調用selector.select(TIMEOUT)等待訂閱的時間發生,然後再采取相應的處理措施。
我們的Echo Server將使用這個接口。然後我們實現Echo Server:



  1. import java.io.IOException;  
  2. import java.net.InetSocketAddress;  
  3. import java.nio.channels.SelectionKey;  
  4. import java.nio.channels.Selector;  
  5. import java.nio.channels.ServerSocketChannel;  
  6. import java.util.Iterator;  
  7.   
  8. public class TCPServerSelector {  
  9.     private static final int BUFSIZE = 256;// Buffersize(bytes)  
  10.     private static final int TIMEOUT = 3000;// Waittimeout(milliseconds)  
  11.   
  12.     public static void main(String[] args) throws IOException {  
  13.         if (args.length < 1) {// Testforcorrect#ofargs  
  14.             throw new IllegalArgumentException("Parameter(s):<Port>...");  
  15.         }  
  16.         // Createaselectortomultiplexlisteningsocketsandconnections  
  17.         Selector selector = Selector.open();  
  18.         // Createlisteningsocketchannelforeachportandregisterselector  
  19.         for (String arg : args) {  
  20.             ServerSocketChannel listnChannel = ServerSocketChannel.open();  
  21.             listnChannel.socket().bind(  
  22.                     new InetSocketAddress(Integer.parseInt(arg)));  
  23.             listnChannel.configureBlocking(false);// mustbenonblockingtoregister  
  24.             // Registerselectorwithchannel.Thereturnedkeyisignored  
  25.             listnChannel.register(selector, SelectionKey.OP_ACCEPT);  
  26.         }  
  27.         // Createahandlerthatwillimplementtheprotocol  
  28.         TCPProtocol protocol = new EchoSelectorProtocol(BUFSIZE);  
  29.         while (true) {// Runforever,processingavailableI/Ooperations  
  30.         // Waitforsomechanneltobeready(ortimeout)  
  31.             if (selector.select(TIMEOUT) == 0) {// returns#ofreadychans  
  32.                 System.out.print(".");  
  33.                 continue;  
  34.             }  
  35.             // GetiteratoronsetofkeyswithI/Otoprocess  
  36.             Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();  
  37.             while (keyIter.hasNext()) {  
  38.                 SelectionKey key = keyIter.next();// Keyisbitmask  
  39.                 // Serversocketchannelhaspendingconnectionrequests?  
  40.                 if (key.isAcceptable()) {  
  41.                     protocol.handleAccept(key);  
  42.                 }  
  43.                 // Clientsocketchannelhaspendingdata?  
  44.                 if (key.isReadable()) {  
  45.                     protocol.handleRead(key);  
  46.                 }  
  47.                 // Clientsocketchannelisavailableforwritingand  
  48.                 // keyisvalid(i.e.,channelnotclosed)?  
  49.                 if (key.isValid() && key.isWritable()) {  
  50.                     protocol.handleWrite(key);  
  51.                 }  
  52.                 keyIter.remove();// removefromsetofselectedkeys  
  53.             }  
  54.         }  
  55.     }  
  56. }  
最後我們實現EchoSelectorProtocol

[c-sharp] view plaincopy
  1. package com.cnblogs.gpcuster;  
  2. import java.nio.channels.SelectionKey;  
  3. import java.nio.channels.SocketChannel;  
  4. import java.nio.channels.ServerSocketChannel;  
  5. import java.nio.ByteBuffer;  
  6. import java.io.IOException;  
  7. public class EchoSelectorProtocol implements TCPProtocol {  
  8.     private int bufSize;// SizeofI/Obuffer  
  9.     public EchoSelectorProtocol(int bufSize) {  
  10.         this.bufSize = bufSize;  
  11.     }  
  12.     public void handleAccept(SelectionKey key) throws IOException {  
  13.         SocketChannel clntChan = ((ServerSocketChannel) key.channel()).accept();  
  14.         clntChan.configureBlocking(false);// Mustbenonblockingtoregister  
  15.         // Registertheselectorwithnewchannelforreadandattachbytebuffer  
  16.         clntChan.register(key.selector(), SelectionKey.OP_READ, ByteBuffer  
  17.                 .allocate(bufSize));  
  18.     }  
  19.     public void handleRead(SelectionKey key) throws IOException {  
  20.         // Clientsocketchannelhaspendingdata  
  21.         SocketChannel clntChan = (SocketChannel) key.channel();  
  22.         ByteBuffer buf = (ByteBuffer) key.attachment();  
  23.         long bytesRead = clntChan.read(buf);  
  24.         if (bytesRead == -1) {// Didtheotherendclose?  
  25.             clntChan.close();  
  26.         } else if (bytesRead > 0) {  
  27.             // Indicateviakeythatreading/writingarebothofinterestnow.  
  28.             key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);  
  29.         }  
  30.     }  
  31.     public void handleWrite(SelectionKey key) throws IOException {  
  32.         /* 
  33.          * Channelisavailableforwriting,andkeyisvalid(i.e.,clientchannel 
  34.          * notclosed). 
  35.          */  
  36.         // Retrievedatareadearlier  
  37.         ByteBuffer buf = (ByteBuffer) key.attachment();  
  38.         buf.flip();// Preparebufferforwriting  
  39.         SocketChannel clntChan = (SocketChannel) key.channel();  
  40.         clntChan.write(buf);  
  41.         if (!buf.hasRemaining()) {// Buffercompletelywritten?  
  42.         // Nothingleft,sonolongerinterestedinwrites  
  43.             key.interestOps(SelectionKey.OP_READ);  
  44.         }  
  45.         buf.compact();// Makeroomformoredatatobereadin  
  46.     }  
  47. }  

在這裏,我們又進一步對Selector注冊了相關的事件:key.interestOps(SelectionKey.OP_READ); 

這樣,我們就實現了基於NIO的Echo 係統。

最後更新:2017-04-03 14:54:18

  上一篇:go Java IO--合並流SequenceInputStream
  下一篇:go 程序猿必看的 幾部電影