AIO实现TimeServer

简介: 目标- 实现返回当前服务器时间的功能- 采用半双工模式(主要是因为采用telnet为客户端,然后telnet默认情况下是半双工)- 客户端连接后,可以发送 time,stop命令. 只有客户端发送stop命令后,服务段才主动断开链路。

目标

- 实现返回当前服务器时间的功能
- 采用半双工模式(主要是因为采用telnet为客户端,然后telnet默认情况下是半双工)
- 客户端连接后,可以发送 time,stop命令. 只有客户端发送stop命令后,服务段才主动断开链路。
- 不考虑读半包和写半包的情况

代码和注释

废话不多说,尽在代码中。直接拷贝即可运行(jdk7或以上)

package com.aio;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
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.Date;
import java.util.concurrent.CountDownLatch;

/**
 * Author :  Rocky
 * Date : 21/12/2016 15:17
 * Description :
 * Test :
 */
public class TimeServer {

    public static void main(String[] args) throws InterruptedException {
        AsynchronousServerSocketChannel assc = null;
        try {
            assc = AsynchronousServerSocketChannel.open();
            assc.bind(new InetSocketAddress(8888));
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }

        doAccept(assc);

        CountDownLatch latch = new CountDownLatch(1);
        latch.await();
    }

    private static void doAccept(AsynchronousServerSocketChannel assc) {
        assc.accept(assc, new AcceptCompletionHandle());
    }

    private static class AcceptCompletionHandle implements CompletionHandler<AsynchronousSocketChannel, AsynchronousServerSocketChannel> {

        @Override
        public void completed(AsynchronousSocketChannel result, AsynchronousServerSocketChannel assc) {
            //继续监听accept事件
            assc.accept(assc, this);

            //开始监听可读时间
            ByteBuffer readBuf = ByteBuffer.allocate(1024);
            result.read(readBuf, readBuf, new ReadCompletionHandler(result));
        }

        @Override
        public void failed(Throwable exc, AsynchronousServerSocketChannel assc) {
            System.out.println("accept异常,继续accept");
            assc.accept(assc, this);
        }
    }

    private static class ReadCompletionHandler implements CompletionHandler<Integer, ByteBuffer> {

        private AsynchronousSocketChannel asc;

        public ReadCompletionHandler(AsynchronousSocketChannel asc) {
            this.asc = asc;
        }

        @Override
        public void completed(Integer result, ByteBuffer readedData) {
            //如果对端链路关闭
            if (result < 0) {
                try {
                    asc.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return;
            }
            //如果读取到对端发送过来的数据
            if (result > 0) {
                readedData.flip();
                byte[] data = new byte[readedData.remaining()];
                readedData.get(data);
                String command = null;
                try {
                    command = new String(data, "UTF-8");
                    if ("time\r\n".equalsIgnoreCase(command)) {
                        doWrite(new Date().toString() + "\r\n");
                    } else if ("stop\r\n".equalsIgnoreCase(command)) {
                        doWriteAndClose("bye.\r\n");
                    } else if ("\r\n".equalsIgnoreCase(command)) {
                        doWrite("\r\n");
                    } else {
                        doWrite("unknown command\r\n");
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    doWrite("server error\r\n");
                }
            }
            //如果未读取到数据
            else {
                //继续尝试读取对端发送的数据
                ByteBuffer readBuf = ByteBuffer.allocate(1024);
                asc.read(readBuf, readBuf, this);
            }
        }

        private void doWriteAndClose(String response) {
            ByteBuffer repBuf = null;
            try {
                repBuf = ByteBuffer.wrap(response.getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if (repBuf != null) {
                asc.write(repBuf, repBuf, new CompletionHandler<Integer, ByteBuffer>() {
                    @Override
                    public void completed(Integer result, ByteBuffer repBuf) {
                        if (repBuf.hasRemaining()) {
                            asc.write(repBuf, repBuf, this);
                        }
                        //写完成后,关闭链路
                        else {
                            try {
                                asc.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void failed(Throwable exc, ByteBuffer repBuf) {
                        exc.printStackTrace();
                        try {
                            asc.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }

        private void doWrite(String response) {
            ByteBuffer repBuf = null;
            try {
                repBuf = ByteBuffer.wrap(response.getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if (repBuf != null) {
                asc.write(repBuf, repBuf, new WriteCompletionHandler(asc, this));
            }
        }

        @Override
        public void failed(Throwable exc, ByteBuffer readedData) {
            exc.printStackTrace();
            try {
                asc.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }


    private static class WriteCompletionHandler implements CompletionHandler<Integer, ByteBuffer> {

        private AsynchronousSocketChannel asc;

        private ReadCompletionHandler rch;

        public WriteCompletionHandler(AsynchronousSocketChannel asc, ReadCompletionHandler rch) {
            this.asc = asc;
            this.rch = rch;
        }

        @Override
        public void completed(Integer result, ByteBuffer repBuf) {
            if (repBuf.hasRemaining()) {
                asc.write(repBuf, repBuf, this);
            }
            //写完成后(对端读取完成),再尝试读(半双工模式)
            else {
                //继续尝试读取对端发送的数据
                ByteBuffer readBuf = ByteBuffer.allocate(1024);
                asc.read(readBuf, readBuf, rch);
            }
        }

        @Override
        public void failed(Throwable exc, ByteBuffer repBuf) {
            exc.printStackTrace();
            try {
                asc.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

测试

telnet 127.0.0.1 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.


time
Wed Dec 21 17:05:44 CST 2016
time
Wed Dec 21 17:07:44 CST 2016


s
unknown command
f
unknown command


stop
bye.
Connection closed by foreign host.
目录
相关文章
|
Java
BIO,NIO,AIO 有什么区别?
BIO,NIO,AIO 有什么区别? BIO:Block IO 同步阻塞式 IO,就是我们平常使用的传统 IO,它的特点是模式简单使用方便,并发处理能力低。
55 0
|
1月前
|
存储 Linux C语言
Linux C/C++之IO多路复用(aio)
这篇文章介绍了Linux中IO多路复用技术epoll和异步IO技术aio的区别、执行过程、编程模型以及具体的编程实现方式。
82 1
Linux C/C++之IO多路复用(aio)
|
2月前
|
Java
Netty BIO/NIO/AIO介绍
Netty BIO/NIO/AIO介绍
|
3月前
|
缓存 Java UED
BIO、NIO、AIO有什么区别
【8月更文挑战第16天】BIO、NIO、AIO有什么区别
77 4
|
4月前
|
安全 Java Linux
(七)Java网络编程-IO模型篇之从BIO、NIO、AIO到内核select、epoll剖析!
IO(Input/Output)方面的基本知识,相信大家都不陌生,毕竟这也是在学习编程基础时就已经接触过的内容,但最初的IO教学大多数是停留在最基本的BIO,而并未对于NIO、AIO、多路复用等的高级内容进行详细讲述,但这些却是大部分高性能技术的底层核心,因此本文则准备围绕着IO知识进行展开。
165 1
|
6月前
|
消息中间件 网络协议 Java
一文彻底理解BIO、NIO、AIO
一文彻底理解BIO、NIO、AIO
272 0
|
存储 弹性计算 Java
|
消息中间件 存储 网络协议
Linux五种I/O模式 NIO BIO AIO IO多路复用 信号驱动 I/O
Linux五种I/O模式 NIO BIO AIO IO多路复用 信号驱动 I/O
238 0
|
Java Linux API
BIO&NIO&AIO
BIO&NIO&AIO
114 0
|
Java 网络架构
BIO、NIO、AIO的区别
BIO、NIO、AIO的区别
BIO、NIO、AIO的区别