NIO学习笔记(4)-简单echo实例

简介:

echo小例子 

服务端

 

 
  1. import java.io.IOException; 
  2. import java.net.InetSocketAddress; 
  3. import java.net.ServerSocket; 
  4. import java.nio.ByteBuffer; 
  5. import java.nio.channels.SelectionKey; 
  6. import java.nio.channels.Selector; 
  7. import java.nio.channels.ServerSocketChannel; 
  8. import java.nio.channels.SocketChannel; 
  9. import java.util.Iterator; 
  10.  
  11.  
  12. public class Ex2Server { 
  13.  
  14.     /** 
  15.      * @param args 
  16.      * @throws IOException  
  17.      */ 
  18.     public static void main(String[] args) throws IOException { 
  19.         //第一件事是创建一个 Selector 
  20.         Selector selector = Selector.open(); 
  21.          
  22.         //要监听的每一个端口都需要有一个 ServerSocketChannel  
  23.         ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); 
  24.         serverSocketChannel.configureBlocking(false); 
  25.  
  26.         ServerSocket serverSocket = serverSocketChannel.socket(); 
  27.         serverSocket.bind(new InetSocketAddress(12345));//绑定一个端口 
  28.          
  29.         //SelectionKey 代表这个通道在此 Selector 上的这个注册。 
  30.         //当某个 Selector 通知您某个传入事件时,它是通过提供对应于该事件的 SelectionKey 来进行的。 
  31.         //SelectionKey 还可以用于取消通道的注册。 
  32.         SelectionKey selectionKey = serverSocketChannel.register( 
  33.                 selector, SelectionKey.OP_ACCEPT);//注册accept事件 
  34.          
  35.         int num = 0
  36.         ByteBuffer buffer = ByteBuffer.allocate(1024); 
  37.         while(true){ 
  38.             //select方法会阻塞,直到至少有一个已注册的事件发生 
  39.             num = selector.select(); 
  40.              
  41.             Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); 
  42.             SelectionKey key = null
  43.             while(iterator.hasNext()){ 
  44.                  key = iterator.next(); 
  45.                  if(key.isAcceptable()){//accept 
  46.                      ServerSocketChannel channel = (ServerSocketChannel)key.channel(); 
  47.                      //相当于从ServerSocket中accept一个socket 
  48.                      SocketChannel socketChannel = channel.accept(); 
  49.                      socketChannel.configureBlocking(false);//设为非阻塞 
  50.                      socketChannel.register(selector, SelectionKey.OP_READ); 
  51.                       
  52.                  }else if(key.isReadable()){ 
  53.                      SocketChannel channel = (SocketChannel)key.channel(); 
  54.                      int readNum = 0
  55.                      while(readNum != -1){ 
  56.                          buffer.clear(); 
  57.                          channel.read(buffer);//读出 
  58.                           
  59.                          buffer.flip(); 
  60.                          channel.write(buffer); 
  61.                      } 
  62.                      //channel.close(); 
  63.                       
  64.                  }else if(key.isWritable()){ 
  65.                       
  66.                  } 
  67.                  iterator.remove(); 
  68.             } 
  69.         } 
  70.          
  71.     } 
  72.  

客户端

 

 
  1. import java.io.BufferedReader; 
  2. import java.io.IOException; 
  3. import java.io.InputStreamReader; 
  4. import java.io.OutputStreamWriter; 
  5. import java.io.PrintWriter; 
  6. import java.net.InetSocketAddress; 
  7. import java.net.Socket; 
  8. import java.net.SocketAddress; 
  9.  
  10.  
  11. public class Ex2Client { 
  12.  
  13.     /** 
  14.      * @param args 
  15.      * @throws IOException  
  16.      */ 
  17.     public static void main(String[] args) throws IOException { 
  18.         SocketAddress address = new InetSocketAddress("localhost"12345); 
  19.         Socket s = new Socket(); 
  20.         s.connect(address); 
  21.         PrintWriter writer = new PrintWriter( new OutputStreamWriter(s.getOutputStream())); 
  22.         writer.println("abc"); 
  23.         writer.flush(); 
  24.          
  25.         BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream())); 
  26.         System.out.println(reader.readLine()); 
  27.          
  28.         writer.close(); 
  29.         reader.close(); 
  30.         s.close(); 
  31.     } 
  32.  

   如果写入的内容比较多,可以把读跟写分开

 

 
  1. import java.io.IOException; 
  2. import java.net.InetSocketAddress; 
  3. import java.net.ServerSocket; 
  4. import java.nio.ByteBuffer; 
  5. import java.nio.channels.SelectionKey; 
  6. import java.nio.channels.Selector; 
  7. import java.nio.channels.ServerSocketChannel; 
  8. import java.nio.channels.SocketChannel; 
  9. import java.util.Iterator; 
  10.  
  11.  
  12. public class Ex2Server2 { 
  13.  
  14.     /** 
  15.      * @param args 
  16.      * @throws IOException  
  17.      */ 
  18.     public static void main(String[] args) throws IOException { 
  19.         //第一件事是创建一个 Selector 
  20.         Selector selector = Selector.open(); 
  21.          
  22.         //要监听的每一个端口都需要有一个 ServerSocketChannel  
  23.         ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); 
  24.         serverSocketChannel.configureBlocking(false); 
  25.  
  26.         ServerSocket serverSocket = serverSocketChannel.socket(); 
  27.         serverSocket.bind(new InetSocketAddress(12345));//绑定一个端口 
  28.          
  29.         //SelectionKey 代表这个通道在此 Selector 上的这个注册。 
  30.         //当某个 Selector 通知您某个传入事件时,它是通过提供对应于该事件的 SelectionKey 来进行的。 
  31.         //SelectionKey 还可以用于取消通道的注册。 
  32.         SelectionKey selectionKey = serverSocketChannel.register( 
  33.                 selector, SelectionKey.OP_ACCEPT);//注册accept事件 
  34.          
  35.         int num = 0
  36.         ByteBuffer buffer = ByteBuffer.allocate(1024); 
  37.         while(true){ 
  38.             //select方法会阻塞,直到至少有一个已注册的事件发生 
  39.             num = selector.select(); 
  40.              
  41.             Iterator<SelectionKey> iterator = selector.selectedKeys().iterator(); 
  42.             SelectionKey key = null
  43.             while(iterator.hasNext()){ 
  44.                  key = iterator.next(); 
  45.                  if(key.isAcceptable()){//accept 
  46.                      ServerSocketChannel channel = (ServerSocketChannel)key.channel(); 
  47.                      //相当于从ServerSocket中accept一个socket 
  48.                      SocketChannel socketChannel = channel.accept(); 
  49.                      socketChannel.configureBlocking(false);//设为非阻塞 
  50.                      socketChannel.register(selector, SelectionKey.OP_READ); 
  51.                       
  52.                  }else if(key.isReadable()){ 
  53.                      SocketChannel channel = (SocketChannel)key.channel(); 
  54.                      int readNum = 1
  55.                      while(readNum > 0){ 
  56.                          buffer.clear(); 
  57.                          readNum = channel.read(buffer);//读出 
  58.                           
  59.                          buffer.flip(); 
  60.                          //channel.write(buffer); 
  61.                      } 
  62.                      channel.register(selector, SelectionKey.OP_WRITE); 
  63.                      //channel.close(); 
  64.                       
  65.                  }else if(key.isWritable()){ 
  66.                      SocketChannel channel = (SocketChannel)key.channel(); 
  67.                      buffer.clear(); 
  68.                      buffer.put("测试\r\n".getBytes()); 
  69.                      buffer.flip(); 
  70.                      channel.write(buffer);
  71.  
  72.                     //取消写入key的注册,不然一直可写 
  73.                      key.cancel(); 
  74. //改正:key.cancel会把channel也关闭,这里设置OPS为读,也就把写给反注册掉了
  75. key.interestOps(SelectionKey.OP_READ);
  76.                  } 
  77.                  iterator.remove(); 
  78.             } 
  79.         } 
  80.  
  81.     } 
  82.  

   



本文转自 dogegg250 51CTO博客,原文链接:http://blog.51cto.com/jianshusoft/692761,如需转载请自行联系原作者

相关文章
|
缓存 Java
JAVA NIO学习笔记一
JAVA NIO学习笔记一
64 0
|
大数据 开发者 容器
网络编程:IO 通信模型—BIO&amp;NIO|学习笔记
快速学习网络编程:IO 通信模型—BIO&amp;NIO
123 0
网络编程:IO 通信模型—BIO&amp;NIO|学习笔记
|
缓存 Java Unix
02、Netty学习笔记—(NIO网络编程和IO模型)(二)
02、Netty学习笔记—(NIO网络编程和IO模型)(二)
02、Netty学习笔记—(NIO网络编程和IO模型)(二)
|
存储 负载均衡 监控
02、Netty学习笔记—(NIO网络编程和IO模型)(一)
02、Netty学习笔记—(NIO网络编程和IO模型)(一)
02、Netty学习笔记—(NIO网络编程和IO模型)(一)
|
存储 Java API
NIO 学习笔记(一)初遇
NIO 学习笔记(一)初遇
NIO 学习笔记(一)初遇
|
前端开发 Java Linux
NIO学习笔记(三) 甚欢篇
NIO学习笔记(三) 甚欢篇
NIO学习笔记(三) 甚欢篇
|
Java Apache
学习socket nio 之 mina实例(1)
学习socket nio 之 mina实例(1)
132 0
学习socket nio 之 mina实例(1)
学习socket nio 之 mina实例(2)
学习socket nio 之 mina实例(2)
143 0
|
Java Windows
Java NIO(十八)实例
package com.nio; import java.io.IOException; import java.net.InetSocketAddress; import java.
802 0