Java分散開発TCP / IP NIOノンブロッキングソケット((システム間の通信を実現するメッセージモードに基づく))

差出人:https : //www.iteye.com/blog/mars914-1238353

Javaでは、TCP / IP + NIOシステム間通信は、java.nio.channelsのChannelおよびSelectorの関連クラスに基づいて実現できます。

 

システム間通信に使用されます。SocketChannelとServerSocketChannelが使用されます。SocketChannelは、接続の確立、イベントの監視、読み取りおよび書き込み操作に使用されます。ServerSocketChannelは、ポートの監視と接続イベントの監視に使用されます。セレクタを使用して、処理するイベントがあるかどうかを取得できます。

 

サーバーJavaコード:

Javaコード   お気に入りのコード
  1. パッケージcom.java.distributed.message.tcpip;  
  2.   
  3. import java.io.IOException;  
  4. import java.net.InetSocketAddress;  
  5. import java.net.ServerSocket;  
  6. import java.nio.ByteBuffer;  
  7. import java.nio.channels.SelectionKey;  
  8. import java.nio.channels.Selector;  
  9. import java.nio.channels.ServerSocketChannel;  
  10. import java.nio.channels.SocketChannel;  
  11. import java.nio.charset.Charset;  
  12.   
  13. パブリック  クラスNIOServer {  
  14.   
  15.     / ** 
  16.      * @param args 
  17.      * @throws IOException  
  18.      * /  
  19.     public  static  void main(String [] args)  はIOException {をスローします  
  20.         intポート= 7889;  
  21.         //セレクタを開きます  
  22.         Selector selector = Selector.open();  
  23.         //サーバーソケットチャネルを開きます  
  24.         ServerSocketChannel ssc = ServerSocketChannel.open();  
  25.         //このチャネルに関連付けられているサーバーソケットを取得します  
  26.         ServerSocket serverSocket = ssc.socket();  
  27.         // ServerSocketを特定のアドレス(IPアドレスとポート番号)にバインドします  
  28.         serverSocket.bind(new InetSocketAddress(port));  
  29.         System.out.println("server listen on port:" + port);  
  30.           
  31.         //チャネルのブロッキングモードを調整します  
  32.         ssc.configureBlocking(false);  
  33.         //このチャネルを指定されたセレクタに登録し、選択キーを返します。SelectionKey.OP_ACCEPT-ソケット受け入れ操作の操作セットビット     
  34.         ssc.register(selector、SelectionKey.OP_ACCEPT);  
  35.           
  36.         while(true){  
  37.             //タイムアウト:正、チャネルの準備が整うまで最大でmsタイムアウトブロックする;ゼロの場合は無期限にブロックする;負でない必要がある  
  38.             int nKeys = selector.select(1000);  
  39.             if(nKeys> 0){  
  40.                   
  41.                 for(SelectionKey key:selector.selectedKeys()){  
  42.                     / *このキーのチャネルが新しいソケット接続を受け入れる準備ができているかどうかをテストします- 
  43.                      *このキーのチャネルがソケット受け入れ操作をサポートしていない場合、このメソッドは常にfalseを返します 
  44.                      * * /  
  45.                     if(key.isAcceptable()){  
  46.                         ServerSocketChannel server =(ServerSocketChannel)key.channel();  
  47.                         SocketChannel sc = server.accept();  
  48.                           
  49.                         if(sc == null){  
  50.                             継続する;  
  51.                         }  
  52.                         sc.configureBlocking(false);  
  53.                         sc.register(selector、SelectionKey.OP_READ);  
  54.                     } else  if(key.isReadable()){  
  55.                         //新しいバイトバッファを割り当てます  
  56.                         ByteBuffer buffer = ByteBuffer.allocate(1024);  
  57.                         SocketChannel sc =(SocketChannel)key.channel();  
  58.                         int readBytes = 0;  
  59.                         文字列message = null;  
  60.                         試す{  
  61.                             int ret;  
  62.                             試す{  
  63.                                 while((ret = sc.read(buffer))> 0){  
  64.                                     readBytes + = ret;  
  65.                                 }  
  66.                                   
  67.                             } catch(Exception e){  
  68.                                 readBytes = 0;  
  69.                                 //無視する  
  70.                             } ようやく{  
  71.                                 //このバッファを逆にします。最初に現在の位置に制限を設定し、次に位置をゼロに設定します  
  72.                                 buffer.flip();  
  73.                             }  
  74.                               
  75.                             if(readBytes> 0){  
  76.                                 message = Charset.forName("UTF-8")。decode(buffer).toString();  
  77.                                 buffer = null;  
  78.                             }  
  79.                         } ようやく{  
  80.                             if(buffer!= null)  
  81.                                 buffer.clear();  
  82.                         }  
  83.                           
  84.                         if(readBytes> 0){  
  85.                             System.out.println("クライアントからのメッセージ:" +メッセージ);  
  86.                             if("quit" .equalsIgnoreCase(message.trim())){  
  87.                                 sc.close();  
  88.                                 selector.close();  
  89.                                 System.out.println("サーバーがシャットダウンされました!");  
  90.                                 System.exit(0);  
  91.                             }  
  92.                             String outMessage = "server response:" + message;  
  93.                             sc.write(Charset.forName("UTF-8")。encode(outMessage));  
  94.                         }  
  95.                           
  96.                     }  
  97.                 }  
  98.                 selector.selectedKeys()。clear();  
  99.             }  
  100.           
  101.         }  
  102.     }  
  103. }  

 

 

クライアントJavaコード:

Javaコード   お気に入りのコード
  1. パッケージcom.java.distributed.message.tcpip;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.IOException;  
  5. import java.io.InputStreamReader;  
  6. import java.net.InetSocketAddress;  
  7. import java.net.SocketAddress;  
  8. import java.nio.ByteBuffer;  
  9. import java.nio.channels.SelectionKey;  
  10. import java.nio.channels.Selector;  
  11. import java.nio.channels.SocketChannel;  
  12. import java.nio.charset.Charset;  
  13.   
  14.   
  15. パブリック  クラスNIOClient {  
  16.   
  17.     / ** 
  18.      * @param args 
  19.      * @throws IOException  
  20.      * /  
  21.     public  static  void main(String [] args)  はIOException {をスローします  
  22.         intポート= 7889;  
  23.         SocketChannel channel = SocketChannel.open();  
  24.         channel.configureBlocking(false);  
  25.           
  26.         SocketAddress target = new InetSocketAddress("127.0.0.1"、port);  
  27.         channel.connect(target);  
  28.         Selector selector = Selector.open();  
  29.         //ソケット接続操作の操作セットビット  
  30.         channel.register(selector、SelectionKey.OP_CONNECT);  
  31.         BufferedReader systemIn = new BufferedReader(new InputStreamReader(System.in));  
  32.           
  33.         while(true){  
  34.             if(channel.isConnected()){  
  35.                 文字列command = systemIn.readLine();  
  36.                 channel.write(Charset.forName("UTF-8")。encode(コマンド));  
  37.                   
  38.                 if(command == null || "quit" .equalsIgnoreCase(command.trim())){  
  39.                     systemIn.close();  
  40.                     channel.close();  
  41.                     selector.close();  
  42.                     System.out.println("Client quit!");  
  43.                     System.exit(0);  
  44.                 }  
  45.             }  
  46.             int nKeys = selector.select(1000);  
  47.             if(nKeys> 0){  
  48.                 for(SelectionKey key:selector.selectedKeys()){  
  49.                     if(key.isConnectable()){  
  50.                         SocketChannel sc =(SocketChannel)key.channel();  
  51.                         sc.configureBlocking(false);  
  52.                         sc.register(selector、SelectionKey.OP_READ);  
  53.                         sc.finishConnect();  
  54.                     } else  if(key.isReadable()){  
  55.                         ByteBuffer buffer = ByteBuffer.allocate(1024);  
  56.                         SocketChannel sc =(SocketChannel)key.channel();  
  57.                         int readBytes = 0;  
  58.                         試す{  
  59.                             int ret = 0;  
  60.                             試す{  
  61.                                 while((ret = sc.read(buffer))> 0){  
  62.                                     バイト= K +を読み取ります。  
  63.                                 }  
  64.                             } ようやく{  
  65.                                 buffer.flip();  
  66.                             }  
  67.                             if(readBytes>  0){     
  68.                                 System.out.println(Charset.forName("UTF-8")     
  69.                                         .decode(buffer).toString());     
  70.                                 buffer =  null;     
  71.                             }     
  72.   
  73.                         } ついに{     
  74.                             if(buffer!=  null){     
  75.                                 buffer.clear();     
  76.                             }  
  77.                         }  
  78.                     }  
  79.                 }  
  80.                     selector.selectedKeys()。clear();     
  81.             }  
  82.         }  
  83.     }  
  84.   
  85. }  

おすすめ

転載: www.cnblogs.com/sharpest/p/12702762.html