AIO

AIO編程

    NIO 2.0引入了新的異步通道的概念,並提供了異步文件通道和異步套接字通道的實現。

    異步的套接字通道時真正的異步非阻塞I/O,對應於UNIX網絡編程中的事件驅動I/O(AIO)。他不需要過多的Selector對註冊的通道進行輪詢即可實現異步讀寫,從而簡化了NIO的編程模型。

    直接上代碼吧。

3.1、Server端代碼

    Server:

package com.anxpp.io.calculator.aio.server;
/**
 * AIO服務端
 * @author yangtao__anxpp.com
 * @version 1.0
 */
public class Server {
    private static int DEFAULT_PORT = 12345;
    private static AsyncServerHandler serverHandle;
    public volatile static long clientCount = 0;
    public static void start(){
        start(DEFAULT_PORT);
    }
    public static synchronized void start(int port){
        if(serverHandle!=null)
            return;
        serverHandle = new AsyncServerHandler(port);
        new Thread(serverHandle,"Server").start();
    }
    public static void main(String[] args){
        Server.start();
    }

}

AsyncServerHandler:

package com.anxpp.io.calculator.aio.server;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.CountDownLatch;
public class AsyncServerHandler implements Runnable {
    public CountDownLatch latch;
    public AsynchronousServerSocketChannel channel;
    public AsyncServerHandler(int port) {
        try {
            //創建服務端通道
            channel = AsynchronousServerSocketChannel.open();
            //綁定端口
            channel.bind(new InetSocketAddress(port));
            System.out.println("服務器已啓動,端口號:" + port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        //CountDownLatch初始化
        //它的作用:在完成一組正在執行的操作之前,允許當前的現場一直阻塞
        //此處,讓現場在此阻塞,防止服務端執行完成後退出
        //也可以使用while(true)+sleep
        //生成環境就不需要擔心這個問題,以爲服務端是不會退出的
        latch = new CountDownLatch(1);
        //用於接收客戶端的連接
        channel.accept(this,new AcceptHandler());
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

  AcceptHandler:

package com.anxpp.io.calculator.aio.server;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
//作爲handler接收客戶端連接
public class AcceptHandler implements CompletionHandler<AsynchronousSocketChannel, AsyncServerHandler> {
    @Override
    public void completed(AsynchronousSocketChannel channel,AsyncServerHandler serverHandler) {
        //繼續接受其他客戶端的請求
        Server.clientCount++;
        System.out.println("連接的客戶端數:" + Server.clientCount);
        serverHandler.channel.accept(serverHandler, this);
        //創建新的Buffer
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        //異步讀  第三個參數爲接收消息回調的業務Handler
        channel.read(buffer, buffer, new ReadHandler(channel));
    }
    @Override
    public void failed(Throwable exc, AsyncServerHandler serverHandler) {
        exc.printStackTrace();
        serverHandler.latch.countDown();
    }
}


ReadHandler:


  1. package com.anxpp.io.calculator.aio.server;
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.nio.ByteBuffer;
    import java.nio.channels.AsynchronousSocketChannel;
    import java.nio.channels.CompletionHandler;
    import com.anxpp.io.utils.Calculator;
    public class ReadHandler implements CompletionHandler<Integer, ByteBuffer> {
        //用於讀取半包消息和發送應答
        private AsynchronousSocketChannel channel;
        public ReadHandler(AsynchronousSocketChannel channel) {
                this.channel = channel;
        }
        //讀取到消息後的處理
        @Override
        public void completed(Integer result, ByteBuffer attachment) {
            //flip操作
            attachment.flip();
            //根據
            byte[] message = new byte[attachment.remaining()];
            attachment.get(message);
            try {
                String expression = new String(message, "UTF-8");
                System.out.println("服務器收到消息: " + expression);
                String calrResult = null;
                try{
                    calrResult = Calculator.cal(expression).toString();
                }catch(Exception e){
                    calrResult = "計算錯誤:" + e.getMessage();
                }
                //向客戶端發送消息
                doWrite(calrResult);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        //發送消息
        private void doWrite(String result) {
            byte[] bytes = result.getBytes();
            ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
            writeBuffer.put(bytes);
            writeBuffer.flip();
            //異步寫數據 參數與前面的read一樣
            channel.write(writeBuffer, writeBuffer,new CompletionHandler<Integer, ByteBuffer>() {
                @Override
                public void completed(Integer result, ByteBuffer buffer) {
                    //如果沒有發送完,就繼續發送直到完成
                    if (buffer.hasRemaining())
                        channel.write(buffer, buffer, this);
                    else{
                        //創建新的Buffer
                        ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                        //異步讀  第三個參數爲接收消息回調的業務Handler
                        channel.read(readBuffer, readBuffer, new ReadHandler(channel));
                    }
                }
                @Override
                public void failed(Throwable exc, ByteBuffer attachment) {
                    try {
                        channel.close();
                    } catch (IOException e) {
                    }
                }
            });
        }
        @Override
        public void failed(Throwable exc, ByteBuffer attachment) {
            try {
                this.channel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

}

OK,這樣就已經完成了,其實說起來也簡單,雖然代碼感覺很多,但是API比NIO的使用起來真的簡單多了,主要就是監聽、讀、寫等各種CompletionHandler。此處本應有一個WriteHandler的,確實,我們在ReadHandler中,以一個匿名內部類實現了它。

    下面看客戶端代碼。

3.2、Client端代碼

    Client:

package com.anxpp.io.calculator.aio.client;
import java.util.Scanner;
public class Client {
    private static String DEFAULT_HOST = "127.0.0.1";
    private static int DEFAULT_PORT = 12345;
    private static AsyncClientHandler clientHandle;
    public static void start(){
        start(DEFAULT_HOST,DEFAULT_PORT);
    }
    public static synchronized void start(String ip,int port){
        if(clientHandle!=null)
            return;
        clientHandle = new AsyncClientHandler(ip,port);
        new Thread(clientHandle,"Client").start();
    }
    //向服務器發送消息
    public static boolean sendMsg(String msg) throws Exception{
        if(msg.equals("q")) return false;
        clientHandle.sendMsg(msg);
        return true;
    }
    @SuppressWarnings("resource")
    public static void main(String[] args) throws Exception{
        Client.start();
        System.out.println("請輸入請求消息:");
        Scanner scanner = new Scanner(System.in);
        while(Client.sendMsg(scanner.nextLine()));
    }

}

AsyncClientHandler:

package com.anxpp.io.calculator.aio.client;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;
public class AsyncClientHandler implements CompletionHandler<Void, AsyncClientHandler>, Runnable {
    private AsynchronousSocketChannel clientChannel;
    private String host;
    private int port;
    private CountDownLatch latch;
    public AsyncClientHandler(String host, int port) {
        this.host = host;
        this.port = port;
        try {
            //創建異步的客戶端通道
            clientChannel = AsynchronousSocketChannel.open();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        //創建CountDownLatch等待
        latch = new CountDownLatch(1);
        //發起異步連接操作,回調參數就是這個類本身,如果連接成功會回調completed方法
        clientChannel.connect(new InetSocketAddress(host, port), this, this);
        try {
            latch.await();
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        try {
            clientChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //連接服務器成功
    //意味着TCP三次握手完成
    @Override
    public void completed(Void result, AsyncClientHandler attachment) {
        System.out.println("客戶端成功連接到服務器...");
    }
    //連接服務器失敗
    @Override
    public void failed(Throwable exc, AsyncClientHandler attachment) {
        System.err.println("連接服務器失敗...");
        exc.printStackTrace();
        try {
            clientChannel.close();
            latch.countDown();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //向服務器發送消息
    public void sendMsg(String msg){
        byte[] req = msg.getBytes();
        ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
        writeBuffer.put(req);
        writeBuffer.flip();
        //異步寫
        clientChannel.write(writeBuffer, writeBuffer,new WriteHandler(clientChannel, latch));
    }

}

 WriteHandler:

package com.anxpp.io.calculator.aio.client;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;
public class WriteHandler implements CompletionHandler<Integer, ByteBuffer> {
    private AsynchronousSocketChannel clientChannel;
    private CountDownLatch latch;
    public WriteHandler(AsynchronousSocketChannel clientChannel,CountDownLatch latch) {
        this.clientChannel = clientChannel;
        this.latch = latch;
    }
    @Override
    public void completed(Integer result, ByteBuffer buffer) {
        //完成全部數據的寫入
        if (buffer.hasRemaining()) {
            clientChannel.write(buffer, buffer, this);
        }
        else {
            //讀取數據
            ByteBuffer readBuffer = ByteBuffer.allocate(1024);
            clientChannel.read(readBuffer,readBuffer,new ReadHandler(clientChannel, latch));
        }
    }
    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
        System.err.println("數據發送失敗...");
        try {
            clientChannel.close();
            latch.countDown();
        } catch (IOException e) {
        }
    }

}

這個API使用起來真的是很順手。

    3.3、測試

    Test:

package com.anxpp.io.calculator.aio;
import java.util.Scanner;
import com.anxpp.io.calculator.aio.client.Client;
import com.anxpp.io.calculator.aio.server.Server;
/**
 * 測試方法
 * @author yangtao__anxpp.com
 * @version 1.0
 */
public class Test {
    //測試主方法
    @SuppressWarnings("resource")
    public static void main(String[] args) throws Exception{
        //運行服務器
        Server.start();
        //避免客戶端先於服務器啓動前執行代碼
        Thread.sleep(100);
        //運行客戶端
        Client.start();
        System.out.println("請輸入請求消息:");
        Scanner scanner = new Scanner(System.in);
        while(Client.sendMsg(scanner.nextLine()));
    }

}

我們可以在控制檯輸入我們需要計算的算數字符串,服務器就會返回結果,當然,我們也可以運行大量的客戶端,都是沒有問題的,以爲此處設計爲單例客戶端,所以也就沒有演示大量客戶端併發。

    讀者可以自己修改Client類,然後開闢大量線程,並使用構造方法創建很多的客戶端測試。

    下面是其中一次參數的輸出:

下面是其中一次參數的輸出:
  1. 服務器已啓動,端口號:12345
  2. 請輸入請求消息:
  3. 客戶端成功連接到服務器...
  4. 連接的客戶端數:1
  5. 123456+789+456
  6. 服務器收到消息: 123456+789+456
  7. 客戶端收到結果:124701
  8. 9526*56
  9. 服務器收到消息: 9526*56
  10. 客戶端收到結果:533456
  11. ...

    AIO是真正的異步非阻塞的,所以,在面對超級大量的客戶端,更能得心應手。

    下面就比較一下,幾種I/O編程的優缺點。










發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章