Java NIO——5 基于非阻塞编程NIO的例子

转自出处:http://blog.csdn.net/chenxuegui1234/article/details/17979725


之前,写的大多都是一些NIO知识点,没有贴出实例,可能看起来比较晦涩,下面是一个基于非阻塞的nio实例


Server:

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * 服务器端 
  3.  *  
  4.  * @author chenxuegui 
  5.  *  
  6.  */  
  7. public class MyServer  
  8. {  
  9.   
  10.     public static void main(String args[]) throws Exception  
  11.     {  
  12.         MyServer server = new MyServer(8080);  
  13.         server.listen();  
  14.     }  
  15.   
  16.     // 接受和发送数据缓冲区  
  17.     private ByteBuffer send = ByteBuffer.allocate(1024);  
  18.     private ByteBuffer receive = ByteBuffer.allocate(1024);  
  19.   
  20.     public int port = 0;  
  21.   
  22.     ServerSocketChannel ssc = null;  
  23.   
  24.     Selector selector = null;  
  25.   
  26.     public MyServer(int port) throws Exception  
  27.     {  
  28.         // 打开服务器套接字通道  
  29.         ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();  
  30.         // 服务器配置为非阻塞  
  31.         serverSocketChannel.configureBlocking(false);  
  32.         // 检索与此通道关联的服务器套接字  
  33.         ServerSocket serverSocket = serverSocketChannel.socket();  
  34.         // 进行服务的绑定  
  35.         serverSocket.bind(new InetSocketAddress(port));  
  36.         // 通过open()方法找到Selector  
  37.         selector = Selector.open();  
  38.   
  39.         // 注册到selector,等待连接  
  40.         serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);  
  41.         System.out.println("Server Start----8888:");  
  42.           
  43.         // 向发送缓冲区加入数据  
  44.         send.put("data come from server".getBytes());  
  45.     }  
  46.   
  47.     // 监听  
  48.     private void listen() throws IOException  
  49.     {  
  50.         while (true)  
  51.         {  
  52.             // 选择一组键,并且相应的通道已经打开  
  53.             selector.select();  
  54.             // 返回此选择器的已选择键集。  
  55.             Set<SelectionKey> selectionKeys = selector.selectedKeys();  
  56.             Iterator<SelectionKey> iterator = selectionKeys.iterator();  
  57.             while (iterator.hasNext())  
  58.             {  
  59.                 SelectionKey selectionKey = iterator.next();  
  60.   
  61.                 // 这里记得手动的把他remove掉,不然selector中的selectedKeys集合不会自动去除  
  62.                 iterator.remove();  
  63.                 dealKey(selectionKey);  
  64.             }  
  65.         }  
  66.     }  
  67.   
  68.     // 处理请求  
  69.     private void dealKey(SelectionKey selectionKey) throws IOException  
  70.     {  
  71.   
  72.         ServerSocketChannel server = null;  
  73.         SocketChannel client = null;  
  74.         String receiveText;  
  75.         String sendText;  
  76.         int count = 0;  
  77.   
  78.         // 测试此键的通道是否已准备好接受新的套接字连接。  
  79.         if (selectionKey.isAcceptable())  
  80.         {  
  81.             // 返回为之创建此键的通道。  
  82.             server = (ServerSocketChannel) selectionKey.channel();  
  83.   
  84.             // 此方法返回的套接字通道(如果有)将处于阻塞模式。  
  85.             client = server.accept();  
  86.             // 配置为非阻塞  
  87.             client.configureBlocking(false);  
  88.             // 注册到selector,等待连接  
  89.             client.register(selector, SelectionKey.OP_READ  
  90.                     | SelectionKey.OP_WRITE);  
  91.         }  
  92.         else  
  93.             if (selectionKey.isReadable())  
  94.             {  
  95.                 // 返回为之创建此键的通道。  
  96.                 client = (SocketChannel) selectionKey.channel();  
  97.                 // 将缓冲区清空以备下次读取  
  98.                 receive.clear();  
  99.                 // 读取服务器发送来的数据到缓冲区中  
  100.                 client.read(receive);  
  101.   
  102.                 System.out.println(new String(receive.array()));  
  103.                   
  104.                 selectionKey.interestOps(SelectionKey.OP_WRITE);  
  105.             }  
  106.             else  
  107.                 if (selectionKey.isWritable())  
  108.                 {  
  109.                     // 将缓冲区清空以备下次写入  
  110.                     send.flip();  
  111.                     // 返回为之创建此键的通道。  
  112.                     client = (SocketChannel) selectionKey.channel();  
  113.   
  114.                     // 输出到通道  
  115.                     client.write(send);  
  116.                       
  117.                     selectionKey.interestOps(SelectionKey.OP_READ);  
  118.                 }  
  119.     }  
  120. }  


Client:

[java]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * 客户端 
  3.  *  
  4.  * @author chenxuegui 
  5.  *  
  6.  */  
  7. public class MyClient  
  8. {  
  9.     public static void main(String args[])  
  10.     {  
  11.         try  
  12.         {  
  13.             MyClient client = new MyClient();  
  14.             client.work(8085);  
  15.         } catch (IOException e)  
  16.         {  
  17.             // TODO Auto-generated catch block  
  18.             e.printStackTrace();  
  19.         }  
  20.     }  
  21.   
  22.     SocketChannel sc = null;  
  23.   
  24.     Selector selector = null;  
  25.   
  26.     // 发送接收缓冲区  
  27.     ByteBuffer send = ByteBuffer.wrap("data come from client".getBytes());  
  28.     ByteBuffer receive = ByteBuffer.allocate(1024);  
  29.   
  30.     public void work(int port) throws IOException  
  31.     {  
  32.   
  33.         try  
  34.         {  
  35.             sc = SocketChannel.open();  
  36.             selector = selector.open();  
  37.   
  38.             // 注册为非阻塞通道  
  39.             sc.configureBlocking(false);  
  40.   
  41.             sc.connect(new InetSocketAddress("localhost"8080));  
  42.   
  43.             sc.register(selector, SelectionKey.OP_CONNECT|SelectionKey.OP_READ|SelectionKey.OP_WRITE);  
  44.   
  45.         } catch (IOException e)  
  46.         {  
  47.             // TODO Auto-generated catch block  
  48.             e.printStackTrace();  
  49.         }  
  50.   
  51.         // Set<SelectionKey> selectionKeys = null;  
  52.         while (true)  
  53.         {  
  54.             // 选择  
  55.             if (selector.select() == 0)  
  56.             {  
  57.                 continue;  
  58.             }  
  59.   
  60.             Iterator<SelectionKey> it = selector.selectedKeys().iterator();  
  61.   
  62.             while (it.hasNext())  
  63.             {  
  64.                 SelectionKey key = it.next();  
  65.   
  66.                 // 必须由程序员手动操作  
  67.                 it.remove();  
  68.                   
  69.                 sc = (SocketChannel) key.channel();  
  70.   
  71.                 if (key.isConnectable())  
  72.                 {  
  73.                     if (sc.isConnectionPending())  
  74.                     {  
  75.                         // 结束连接,以完成整个连接过程  
  76.                         sc.finishConnect();  
  77.                         System.out.println("connect completely");  
  78.   
  79.                         try  
  80.                         {  
  81.                             sc.write(send);  
  82.                         } catch (IOException e)  
  83.                         {  
  84.                             // TODO Auto-generated catch block  
  85.                             e.printStackTrace();  
  86.                         }  
  87.                           
  88. //                      sc.register(selector, SelectionKey.OP_READ|SelectionKey.OP_WRITE);  
  89.                     }  
  90.   
  91.                 }  
  92.                 else  
  93.                     if (key.isReadable())  
  94.                     {  
  95.                         try  
  96.                         {  
  97.                             receive.clear();  
  98.   
  99.                             sc.read(receive);  
  100.   
  101.                             System.out.println(new String(receive.array()));  
  102.   
  103.                         } catch (IOException e)  
  104.                         {  
  105.                             // TODO Auto-generated catch block  
  106.                             e.printStackTrace();  
  107.                         }  
  108.   
  109.                     }  
  110.                     else  
  111.                         if (key.isWritable())  
  112.                         {  
  113.                             receive.flip();  
  114.                             try  
  115.                             {  
  116.                                 send.flip();  
  117.                                   
  118.                                 sc.write(send);  
  119.                             } catch (IOException e)  
  120.                             {  
  121.                                 // TODO Auto-generated catch block  
  122.                                 e.printStackTrace();  
  123.                             }  
  124.                         }  
  125.   
  126.             }// end while  
  127.   
  128.         }// end while(true)  
  129.   
  130.     }// end work()  
  131.   
  132. }  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值