JAVA NIO

来源:互联网 发布:linux shell 控制语句 编辑:程序博客网 时间:2024/05/01 11:00
  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.ServerSocketChannel;  
  7. import java.nio.channels.SocketChannel;  
  8. import java.util.Iterator;  
  9.   
  10. /** 
  11.  * NIO服务端 
  12.  * @author 
  13.  */  
  14. public class NIOServer {  
  15.     //通道管理器  
  16.     private Selector selector;  
  17.   
  18.     /** 
  19.      * 获得一个ServerSocket通道,并对该通道做一些初始化的工作 
  20.      * @param port  绑定的端口号 
  21.      * @throws IOException 
  22.      */  
  23.     public void initServer(int port) throws IOException {  
  24.         // 获得一个ServerSocket通道  
  25.         ServerSocketChannel serverChannel = ServerSocketChannel.open();  
  26.         // 设置通道为非阻塞  
  27.         serverChannel.configureBlocking(false);  
  28.         // 将该通道对应的ServerSocket绑定到port端口  
  29.         serverChannel.socket().bind(new InetSocketAddress(port));  
  30.         // 获得一个通道管理器  
  31.         this.selector = Selector.open();  
  32.         //将通道管理器和该通道绑定,并为该通道注册SelectionKey.OP_ACCEPT事件,注册该事件后,  
  33.         //当该事件到达时,selector.select()会返回,如果该事件没到达selector.select()会一直阻塞。  
  34.         serverChannel.register(selector, SelectionKey.OP_ACCEPT);  
  35.     }  
  36.   
  37.     /** 
  38.      * 采用轮询的方式监听selector上是否有需要处理的事件,如果有,则进行处理 
  39.      * @throws IOException 
  40.      */  
  41.     @SuppressWarnings("unchecked")  
  42.     public void listen() throws IOException {  
  43.         System.out.println("服务端启动成功!");  
  44.         // 轮询访问selector  
  45.         while (true) {  
  46.             //当注册的事件到达时,方法返回;否则,该方法会一直阻塞  
  47.             selector.select();  
  48.             // 获得selector中选中的项的迭代器,选中的项为注册的事件  
  49.             Iterator ite = this.selector.selectedKeys().iterator();  
  50.             while (ite.hasNext()) {  
  51.                 SelectionKey key = (SelectionKey) ite.next();  
  52.                 // 删除已选的key,以防重复处理  
  53.                 ite.remove();  
  54.                 // 客户端请求连接事件  
  55.                 if (key.isAcceptable()) {  
  56.                     ServerSocketChannel server = (ServerSocketChannel) key  
  57.                             .channel();  
  58.                     // 获得和客户端连接的通道  
  59.                     SocketChannel channel = server.accept();  
  60.                     // 设置成非阻塞  
  61.                     channel.configureBlocking(false);  
  62.   
  63.                     //在这里可以给客户端发送信息哦  
  64.                     channel.write(ByteBuffer.wrap(new String("向客户端发送了一条信息").getBytes()));  
  65.                     //在和客户端连接成功之后,为了可以接收到客户端的信息,需要给通道设置读的权限。  
  66.                     channel.register(this.selector, SelectionKey.OP_READ);  
  67.                       
  68.                     // 获得了可读的事件  
  69.                 } else if (key.isReadable()) {  
  70.                         read(key);  
  71.                 }  
  72.   
  73.             }  
  74.   
  75.         }  
  76.     }  
  77.     /** 
  78.      * 处理读取客户端发来的信息 的事件 
  79.      * @param key 
  80.      * @throws IOException  
  81.      */  
  82.     public void read(SelectionKey key) throws IOException{  
  83.         // 服务器可读取消息:得到事件发生的Socket通道  
  84.         SocketChannel channel = (SocketChannel) key.channel();  
  85.         // 创建读取的缓冲区  
  86.         ByteBuffer buffer = ByteBuffer.allocate(10);  
  87.         channel.read(buffer);  
  88.         byte[] data = buffer.array();  
  89.         String msg = new String(data).trim();  
  90.         System.out.println("服务端收到信息:"+msg);  
  91.         ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes());  
  92.         channel.write(outBuffer);// 将消息回送给客户端  
  93.     }  
  94.       
  95.     /** 
  96.      * 启动服务端测试 
  97.      * @throws IOException  
  98.      */  
  99.     public static void main(String[] args) throws IOException {  
  100.         NIOServer server = new NIOServer();  
  101.         server.initServer(8000);  
  102.         server.listen();  
  103.     }  
  104.   
  105. }  




  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.   
  9. /** 
  10.  * NIO客户端 
  11.  * @author 
  12.  */  
  13. public class NIOClient {  
  14.     //通道管理器  
  15.     private Selector selector;  
  16.   
  17.     /** 
  18.      * 获得一个Socket通道,并对该通道做一些初始化的工作 
  19.      * @param ip 连接的服务器的ip 
  20.      * @param port  连接的服务器的端口号          
  21.      * @throws IOException 
  22.      */  
  23.     public void initClient(String ip,int port) throws IOException {  
  24.         // 获得一个Socket通道  
  25.         SocketChannel channel = SocketChannel.open();  
  26.         // 设置通道为非阻塞  
  27.         channel.configureBlocking(false);  
  28.         // 获得一个通道管理器  
  29.         this.selector = Selector.open();  
  30.           
  31.         // 客户端连接服务器,其实方法执行并没有实现连接,需要在listen()方法中调  
  32.         //用channel.finishConnect();才能完成连接  
  33.         channel.connect(new InetSocketAddress(ip,port));  
  34.         //将通道管理器和该通道绑定,并为该通道注册SelectionKey.OP_CONNECT事件。  
  35.         channel.register(selector, SelectionKey.OP_CONNECT);  
  36.     }  
  37.   
  38.     /** 
  39.      * 采用轮询的方式监听selector上是否有需要处理的事件,如果有,则进行处理 
  40.      * @throws IOException 
  41.      */  
  42.     @SuppressWarnings("unchecked")  
  43.     public void listen() throws IOException {  
  44.         // 轮询访问selector  
  45.         while (true) {  
  46.             selector.select();  
  47.             // 获得selector中选中的项的迭代器  
  48.             Iterator ite = this.selector.selectedKeys().iterator();  
  49.             while (ite.hasNext()) {  
  50.                 SelectionKey key = (SelectionKey) ite.next();  
  51.                 // 删除已选的key,以防重复处理  
  52.                 ite.remove();  
  53.                 // 连接事件发生  
  54.                 if (key.isConnectable()) {  
  55.                     SocketChannel channel = (SocketChannel) key  
  56.                             .channel();  
  57.                     // 如果正在连接,则完成连接  
  58.                     if(channel.isConnectionPending()){  
  59.                         channel.finishConnect();  
  60.                           
  61.                     }  
  62.                     // 设置成非阻塞  
  63.                     channel.configureBlocking(false);  
  64.   
  65.                     //在这里可以给服务端发送信息哦  
  66.                     channel.write(ByteBuffer.wrap(new String("向服务端发送了一条信息").getBytes()));  
  67.                     //在和服务端连接成功之后,为了可以接收到服务端的信息,需要给通道设置读的权限。  
  68.                     channel.register(this.selector, SelectionKey.OP_READ);  
  69.                       
  70.                     // 获得了可读的事件  
  71.                 } else if (key.isReadable()) {  
  72.                         read(key);  
  73.                 }  
  74.   
  75.             }  
  76.   
  77.         }  
  78.     }  
  79.     /** 
  80.      * 处理读取服务端发来的信息 的事件 
  81.      * @param key 
  82.      * @throws IOException  
  83.      */  
  84.     public void read(SelectionKey key) throws IOException{  
  85.         //和服务端的read方法一样  
  86.     }  
  87.       
  88.       
  89.     /** 
  90.      * 启动客户端测试 
  91.      * @throws IOException  
  92.      */  
  93.     public static void main(String[] args) throws IOException {  
  94.         NIOClient client = new NIOClient();  
  95.         client.initClient("localhost",8000);  
  96.         client.listen();  
  97.     }  
  98.   
  99. }  

0 0
原创粉丝点击