AsyncTimeServer实例

基于操作系统内核的服务器版本,与内核交互较多所以基本都是嵌套回调执行

package aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;

/**
 * 启动服务端监听
 * @author DXCyber409
 */
public class AsyncTimeServer {

    public static void main(String[] args) {
        AsyncTimeServerHandler timeServer = new AsyncTimeServerHandler(9999);
        new Thread(timeServer, "AIO-AsyncTimeServerHandler-001").start();
    }

}

/**
 * 服务端
 * @author DXCyber409
 */
class AsyncTimeServerHandler implements Runnable {

    private int port;
    
    CountDownLatch latch;
    AsynchronousServerSocketChannel asynchronousServerSocketChannel;

    public AsyncTimeServerHandler(int port) {
        this.port = port;
        try {
            asynchronousServerSocketChannel = AsynchronousServerSocketChannel.open();
            asynchronousServerSocketChannel.bind(new InetSocketAddress(port));
            System.out.println("The time server is start in port : " + port);
        } catch (IOException ex) {
            ex.printStackTrace();
            System.exit(1);
        }
    }

    @Override
    public void run() {
        latch = new CountDownLatch(1);  // CountDownLatch允许在计数为0之前挂起当前操作线程,防止主线程过早结束
        doAccept();
        try {
            latch.await();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
    
    public void doAccept() {
        asynchronousServerSocketChannel.accept(this, new AcceptCompletionHandler());
    }
}

/**
 * 连接事件完成处理回调器
 * @author DXCyber409
 */
class AcceptCompletionHandler implements CompletionHandler<AsynchronousSocketChannel, AsyncTimeServerHandler>{

    /**
     * 连接成功事件回调
     * @param result
     * @param attachment 
     */
    @Override
    public void completed(AsynchronousSocketChannel result, AsyncTimeServerHandler attachment) {
        attachment.asynchronousServerSocketChannel.accept(attachment, this);
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        result.read(buffer, buffer, new ReadCompletionHandler(result));
    }

    /**
     * 连接失败事件回调
     * @param exc
     * @param attachment 
     */
    @Override
    public void failed(Throwable exc, AsyncTimeServerHandler attachment) {
        exc.printStackTrace();
        attachment.latch.countDown();
    }
    
}

/**
 * 读取事件完成处理回调器
 * @author DXCyber409
 */
class ReadCompletionHandler implements CompletionHandler<Integer, ByteBuffer>{
    
    private AsynchronousSocketChannel channel;
    
    public ReadCompletionHandler(AsynchronousSocketChannel channel) {
        if (this.channel == null) {
            this.channel = channel;
        }
    }

    /**
     * 成功状态回调
     * @param result
     * @param attachment 
     */
    @Override
    public void completed(Integer result, ByteBuffer attachment) {
        attachment.flip();
        byte[] body = new byte[attachment.remaining()];
        attachment.get(body);
        try {
            String req = new String(body);
            System.out.println("The time server receive order : " + req);
            String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(req) 
                    ? new java.util.Date(System.currentTimeMillis()).toString() : "BAD ORDER";
            doWrite(currentTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 分离出写模块
     * @param response 
     */
    private void doWrite(String response) {
        if (response != null && response.trim().length() > 0) {
            byte[] bytes = response.getBytes();
            ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
            writeBuffer.put(bytes);
            writeBuffer.flip();
            channel.write(writeBuffer, writeBuffer,
                new CompletionHandler<Integer, ByteBuffer>() {
                    
                    /**
                     * 成功状态回调
                     * @param result
                     * @param buffer 
                     */
                    @Override
                    public void completed(Integer result, ByteBuffer buffer) {
                        if (buffer.hasRemaining()) {  // 有可能写半包,若真如此则继续写
                            channel.write(buffer, buffer, this);
                        }
                    }

                    /**
                     * 失败状态回调
                     * @param exc
                     * @param attachment 
                     */
                    @Override
                    public void failed(Throwable exc, ByteBuffer attachment) {
                        try {
                            channel.close();
                        } catch(IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            );
        }
    }

    /**
     * 失败状态回调
     * @param exc
     * @param attachment 
     */
    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
        try {
            this.channel.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}

评论

暂无评论