1. package com.keara.niosocket; 
  2. import java.io.IOException;   
  3. import java.net.InetSocketAddress;   
  4. import java.nio.ByteBuffer;   
  5. import java.nio.channels.SocketChannel;   
  6. import java.util.logging.Logger;   
  7.    
  8. /**  
  9.  * NIO客户端  
  10.  * 
  11.  *@author huangyh1 
  12.  */   
  13. public class NioTcpClient {   
  14.    
  15.     private static final Logger log = Logger.getLogger(NioTcpClient.class.getName());   
  16.     private InetSocketAddress inetSocketAddress;   
  17.        
  18.     public NioTcpClient(String hostname, int port) {   
  19.         inetSocketAddress = new InetSocketAddress(hostname, port);   
  20.     }   
  21.        
  22.     /**  
  23.      * 发送请求数据  
  24.      * @param requestData  
  25.      */   
  26.     public void send(String requestData) {   
  27.         try {   
  28.             SocketChannel socketChannel = SocketChannel.open(inetSocketAddress);   
  29.             socketChannel.configureBlocking(false);   
  30.             ByteBuffer byteBuffer = ByteBuffer.allocate(512);   
  31.             socketChannel.write(ByteBuffer.wrap(requestData.getBytes()));   
  32.             while (true) {   
  33.                 byteBuffer.clear();   
  34.                 int readBytes = socketChannel.read(byteBuffer);   
  35.                 if (readBytes > 0) {   
  36.                     byteBuffer.flip();   
  37.                     log.info("Client: readBytes = " + readBytes);   
  38.                     log.info("Client: data = " + new String(byteBuffer.array(), 0, readBytes));   
  39.                     socketChannel.close();   
  40.                     break;   
  41.                 }   
  42.             }   
  43.    
  44.         } catch (IOException e) {   
  45.             e.printStackTrace();   
  46.         }   
  47.     }   
  48.        
  49.     public static void main(String[] args) {   
  50.         String hostname = "localhost";   
  51.         String requestData = "Actions speak louder than words!";   
  52.         int port = 10000;   
  53.         new NioTcpClient(hostname, port).send(requestData);   
  54.     }   
  55. }   

 

 

 

 

 

 

  1. package com.keara.niosocket; 
  2.  
  3. import java.io.IOException; 
  4. import java.net.InetSocketAddress; 
  5. import java.nio.channels.SelectionKey; 
  6. import java.nio.channels.Selector; 
  7. import java.nio.channels.ServerSocketChannel; 
  8. import java.util.Iterator; 
  9. import java.util.Set; 
  10. import java.util.logging.Logger; 
  11.  
  12. /** 
  13.  * NIO服务端 
  14.  *  
  15.  * @author huangyh1 
  16.  */ 
  17. public class NioTcpServer extends Thread { 
  18.  
  19.     private static final Logger log = Logger.getLogger(NioTcpServer.class 
  20.             .getName()); 
  21.     private InetSocketAddress inetSocketAddress; 
  22.     private Handler handler = new ServerHandler(); 
  23.  
  24.     public NioTcpServer(String hostname, int port) { 
  25.         inetSocketAddress = new InetSocketAddress(hostname, port); 
  26.     } 
  27.  
  28.     @Override 
  29.     public void run() { 
  30.         try { 
  31.             Selector selector = Selector.open(); // 打开选择器 
  32.             ServerSocketChannel serverSocketChannel = ServerSocketChannel 
  33.                     .open(); // 打开通道 
  34.             serverSocketChannel.configureBlocking(false); // 非阻塞 
  35.             serverSocketChannel.socket().bind(inetSocketAddress); 
  36.             serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); // 向通道注册选择器和对应事件标识 
  37.             log.info("Server: socket server started."); 
  38.             while (true) { // 轮询 
  39.                 int nKeys = selector.select(); 
  40.                 if (nKeys > 0) { 
  41.                     Set<SelectionKey> selectedKeys = selector.selectedKeys(); 
  42.                     Iterator<SelectionKey> it = selectedKeys.iterator(); 
  43.                     while (it.hasNext()) { 
  44.                         SelectionKey key = it.next(); 
  45.                         if (key.isAcceptable()) { 
  46.                             log.info("Server: SelectionKey is acceptable."); 
  47.                             handler.handleAccept(key); 
  48.                         } else if (key.isReadable()) { 
  49.                             log.info("Server: SelectionKey is readable."); 
  50.                             handler.handleRead(key); 
  51.                         } else if (key.isWritable()) { 
  52.                             log.info("Server: SelectionKey is writable."); 
  53.                             handler.handleWrite(key); 
  54.                         } 
  55.                         it.remove(); 
  56.                     } 
  57.                 } 
  58.             } 
  59.         } catch (IOException e) { 
  60.             e.printStackTrace(); 
  61.         } 
  62.     } 
  63.  
  64.     public static void main(String[] args) { 
  65.         NioTcpServer server = new NioTcpServer("localhost"10000); 
  66.         server.start(); 
  67.     } 

 

  1. package com.keara.niosocket; 
  2.  
  3. import java.io.IOException; 
  4. import java.nio.channels.SelectionKey; 
  5.  
  6. /** 
  7.  * 简单处理器接口 
  8.  *  
  9.  * @author huangyh1 
  10.  */ 
  11. public interface Handler { 
  12.     /** 
  13.      * 处理{@link SelectionKey#OP_ACCEPT}事件 
  14.      *  
  15.      * @param key 
  16.      * @throws IOException 
  17.      */ 
  18.     void handleAccept(SelectionKey key) throws IOException; 
  19.  
  20.     /** 
  21.      * 处理{@link SelectionKey#OP_READ}事件 
  22.      *  
  23.      * @param key 
  24.      * @throws IOException 
  25.      */ 
  26.     void handleRead(SelectionKey key) throws IOException; 
  27.  
  28.     /** 
  29.      * 处理{@link SelectionKey#OP_WRITE}事件 
  30.      *  
  31.      * @param key 
  32.      * @throws IOException 
  33.      */ 
  34.     void handleWrite(SelectionKey key) throws IOException; 

 

  1. package com.keara.niosocket; 
  2.  
  3. import java.io.IOException; 
  4. import java.nio.ByteBuffer; 
  5. import java.nio.channels.SelectionKey; 
  6. import java.nio.channels.ServerSocketChannel; 
  7. import java.nio.channels.SocketChannel; 
  8. import java.util.logging.Logger; 
  9.  
  10. /** 
  11.  * 服务端事件处理实现类 
  12.  *  
  13.  * @author huangyh1 
  14.  */ 
  15. class ServerHandler implements Handler { 
  16.     private static final Logger log = Logger.getLogger(ServerHandler.class 
  17.             .getName()); 
  18.  
  19.     public void handleAccept(SelectionKey key) throws IOException { 
  20.         ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key 
  21.                 .channel(); 
  22.         SocketChannel socketChannel = serverSocketChannel.accept(); 
  23.         log.info("Server: accept client socket " + socketChannel); 
  24.         socketChannel.configureBlocking(false); 
  25.         socketChannel.register(key.selector(), SelectionKey.OP_READ); 
  26.     } 
  27.  
  28.     public void handleRead(SelectionKey key) throws IOException { 
  29.         ByteBuffer byteBuffer = ByteBuffer.allocate(512); 
  30.         SocketChannel socketChannel = (SocketChannel) key.channel(); 
  31.         while (true) { 
  32.             int readBytes = socketChannel.read(byteBuffer); 
  33.             if (readBytes > 0) { 
  34.                 log.info("Server: readBytes = " + readBytes); 
  35.                 log.info("Server: data = " 
  36.                         + new String(byteBuffer.array(), 0, readBytes)); 
  37.                 byteBuffer.flip(); 
  38.                 socketChannel.write(byteBuffer); 
  39.                 break
  40.             } 
  41.         } 
  42.         socketChannel.close(); 
  43.     } 
  44.  
  45.     public void handleWrite(SelectionKey key) throws IOException { 
  46.         ByteBuffer byteBuffer = (ByteBuffer) key.p_w_upload(); 
  47.         byteBuffer.flip(); 
  48.         SocketChannel socketChannel = (SocketChannel) key.channel(); 
  49.         socketChannel.write(byteBuffer); 
  50.         if (byteBuffer.hasRemaining()) { 
  51.             key.interestOps(SelectionKey.OP_READ); 
  52.         } 
  53.         byteBuffer.compact(); 
  54.     }