Java AIO的Socket Demo

来源:互联网 发布:阿里通网络客服电话 编辑:程序博客网 时间:2024/05/17 22:10
同步\异步操作 |  阻塞IO\非阻塞IO理解:

 

同步阻塞

 

同步非阻塞

 

异步非阻塞

 


[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. package com.vdebug.aio.socket;  
  2.   
  3. import java.io.IOException;  
  4. import java.net.InetSocketAddress;  
  5. import java.net.StandardSocketOptions;  
  6. import java.nio.ByteBuffer;  
  7. import java.nio.CharBuffer;  
  8. import java.nio.channels.AsynchronousServerSocketChannel;  
  9. import java.nio.channels.AsynchronousSocketChannel;  
  10. import java.nio.channels.CompletionHandler;  
  11. import java.nio.charset.Charset;  
  12. import java.nio.charset.CharsetDecoder;  
  13.   
  14. /** 
  15.  * Created by pc on 2015/1/5. 
  16.  */  
  17. public class Server {  
  18.     static int PORT = 8080;  
  19.     static int BUFFER_SIZE = 1024;  
  20.     static String CHARSET = "utf-8"//默认编码  
  21.     static CharsetDecoder decoder = Charset.forName(CHARSET).newDecoder(); //解码  
  22.   
  23.     int port;  
  24.     //ByteBuffer buffer;  
  25.     AsynchronousServerSocketChannel serverChannel;  
  26.   
  27.     public Server(int port) throws IOException {  
  28.         this.port = port;  
  29.         //this.buffer = ByteBuffer.allocate(BUFFER_SIZE);  
  30.         this.decoder = Charset.forName(CHARSET).newDecoder();  
  31.     }  
  32.   
  33.     private void listen() throws Exception {  
  34.   
  35.         //打开一个服务通道  
  36.         //绑定服务端口  
  37.         this.serverChannel = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(port), 100);  
  38.         this.serverChannel.accept(thisnew AcceptHandler());  
  39.   
  40.         Thread t = new Thread(new Runnable() {  
  41.             @Override  
  42.             public void run() {  
  43.                 while (true) {  
  44.                     System.out.println("运行中...");  
  45.                     try {  
  46.                         Thread.sleep(2000);  
  47.                     } catch (InterruptedException e) {  
  48.                         e.printStackTrace();  
  49.                     }  
  50.                 }  
  51.             }  
  52.         });  
  53.         t.start();  
  54.   
  55.     }  
  56.   
  57.   
  58.     /** 
  59.      * accept到一个请求时的回调 
  60.      */  
  61.     private class AcceptHandler implements CompletionHandler<AsynchronousSocketChannel, Server> {  
  62.         @Override  
  63.         public void completed(final AsynchronousSocketChannel client, Server attachment) {  
  64.             try {  
  65.                 System.out.println("远程地址:" + client.getRemoteAddress());  
  66.                 //tcp各项参数  
  67.                 client.setOption(StandardSocketOptions.TCP_NODELAY, true);  
  68.                 client.setOption(StandardSocketOptions.SO_SNDBUF, 1024);  
  69.                 client.setOption(StandardSocketOptions.SO_RCVBUF, 1024);  
  70.   
  71.                 if (client.isOpen()) {  
  72.                     System.out.println("client.isOpen:" + client.getRemoteAddress());  
  73.                     final ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);  
  74.                     buffer.clear();  
  75.                     client.read(buffer, client, new ReadHandler(buffer));  
  76.                 }  
  77.   
  78.             } catch (Exception e) {  
  79.                 e.printStackTrace();  
  80.             } finally {  
  81.                 attachment.serverChannel.accept(attachment, this);// 监听新的请求,递归调用。  
  82.             }  
  83.         }  
  84.   
  85.         @Override  
  86.         public void failed(Throwable exc, Server attachment) {  
  87.             try {  
  88.                 exc.printStackTrace();  
  89.             } finally {  
  90.                 attachment.serverChannel.accept(attachment, this);// 监听新的请求,递归调用。  
  91.             }  
  92.         }  
  93.     }  
  94.   
  95.     /** 
  96.      * Read到请求数据的回调 
  97.      */  
  98.     private class ReadHandler implements CompletionHandler<Integer, AsynchronousSocketChannel> {  
  99.   
  100.         private ByteBuffer buffer;  
  101.   
  102.         public ReadHandler(ByteBuffer buffer) {  
  103.             this.buffer = buffer;  
  104.         }  
  105.   
  106.         @Override  
  107.         public void completed(Integer result, AsynchronousSocketChannel attachment) {  
  108.             try {  
  109.                 if (result < 0) {// 客户端关闭了连接  
  110.                     Server.close(attachment);  
  111.                 } else if (result == 0) {  
  112.                     System.out.println("空数据"); // 处理空数据  
  113.                 } else {  
  114.                     // 读取请求,处理客户端发送的数据  
  115.                     buffer.flip();  
  116.                     CharBuffer charBuffer = Server.decoder.decode(buffer);  
  117.                     System.out.println(charBuffer.toString()); //接收请求  
  118.   
  119.                     //响应操作,服务器响应结果  
  120.                     buffer.clear();  
  121.                     String res = "HTTP/1.1 200 OK" + "\r\n\r\n" + "hellworld";  
  122.                     buffer = ByteBuffer.wrap(res.getBytes());  
  123.                     attachment.write(buffer, attachment, new WriteHandler(buffer));//Response:响应。  
  124.                 }  
  125.             } catch (Exception e) {  
  126.                 e.printStackTrace();  
  127.             }  
  128.         }  
  129.   
  130.         @Override  
  131.         public void failed(Throwable exc, AsynchronousSocketChannel attachment) {  
  132.             exc.printStackTrace();  
  133.             Server.close(attachment);  
  134.         }  
  135.     }  
  136.   
  137.     /** 
  138.      * Write响应完请求的回调 
  139.      */  
  140.     private class WriteHandler implements CompletionHandler<Integer, AsynchronousSocketChannel> {  
  141.         private ByteBuffer buffer;  
  142.   
  143.         public WriteHandler(ByteBuffer buffer) {  
  144.             this.buffer = buffer;  
  145.         }  
  146.   
  147.         @Override  
  148.         public void completed(Integer result, AsynchronousSocketChannel attachment) {  
  149.             buffer.clear();  
  150.             Server.close(attachment);  
  151.         }  
  152.   
  153.         @Override  
  154.         public void failed(Throwable exc, AsynchronousSocketChannel attachment) {  
  155.             exc.printStackTrace();  
  156.             Server.close(attachment);  
  157.         }  
  158.     }  
  159.   
  160.     public static void main(String[] args) {  
  161.         try {  
  162.             System.out.println("正在启动服务...");  
  163.             Server server = new Server(PORT);  
  164.             server.listen();  
  165.         } catch (Exception e) {  
  166.             e.printStackTrace();  
  167.         }  
  168.     }  
  169.   
  170.     private static void close(AsynchronousSocketChannel client) {  
  171.         try {  
  172.             client.close();  
  173.         } catch (Exception e) {  
  174.             e.printStackTrace();  
  175.         }  
  176.     }  
  177. }  

运行结果:

 

 

0 0
原创粉丝点击