美文网首页
第一讲 netty 基础与简介

第一讲 netty 基础与简介

作者: 农民工进城 | 来源:发表于2018-05-03 19:57 被阅读0次

    本章要点:

    • 什么是netty
    • 基本概念
    • IO模型

    1.1 什么是netty

    Netty是由JBOSS提供的一个java开源框架。Netty提供异步的、事件驱动的网络应用程序框架和工具,用以快速开发高性能、高可靠性的网络服务器和客户端程序。

    也就是说,Netty 是一个基于NIO的客户、服务器端编程框架,使用Netty 可以确保你快速和简单的开发出一个网络应用,例如实现了某种协议的客户,服务端应用。Netty相当简化和流线化了网络应用的编程开发过程,例如,TCP和UDP的socket服务开发。----来自百度百科

    要想真正的了解netty,首先要了解一些基本概念和IO模型。

    1.2 基本概念

    IO 模型可分为:同步阻塞IO(Blocking IO)、同步非阻塞IO(Non-blocking IO)、IO多路复用(IO Multiplexing)、 异步IO(Asynchronous IO)。要想明白这几种类型的区别,首先要搞清楚以下几个概念:

    1.2.1 异步与同步

    同步与异步是指消息通信机制:

    • 同步:当你调用其他的服务或者某个方法时,在这个服务或者方法返回结果之前,你不能够做别的事情,只能一直等待。
    • 异步: 当调用其他服务或者方法时,调用者立即返回结果。但是实际真正的结果只有处理这个调用的部件在完成后,通过状态、通知和回调来通知调用者。
      同步与异步是对应的,它们是线程之间的关系,两个线程之间要么是同步的,要么是异步的。
    1.2.2 阻塞与非阻塞

    阻塞和非阻塞关注的是程序在等待调用结果(消息,返回值)时的状态,是数据处理的方式。
    - 阻塞:当调用时会将此线程会挂起,直到线程持续等待资源中数据准备完成,返回响应结果。
    - 非阻塞:非阻塞和阻塞的概念相对应,指在不能立刻得到结果之前,该函数不会阻塞当前线程,而会立刻返回。
    阻塞与非阻塞是对同一个线程来说的,在某个时刻,线程要么处于阻塞,要么处于非阻塞。

    1.3 IO模型

    1.3.1 传统的BIO

    传统的BIO是一种同步阻塞的IO,在IO读写该线程都会进行阻塞,无法进行其他操作。该模式是一问一答的模式,所以服务端的线程个数和客户端的并发访问数是1:1的关系,由于线程是JVM非常宝贵的系统资源,当线程数越来越多时,系统会急剧下降,甚至宕机。
    BIO代码示例如下:

    服务端:

    package com.bj58.wuxian.bio;
    import java.io.IOException;
    import java.net.ServerSocket;
    import java.net.Socket;
    public class TimeServer {
        
        public static void main(String[] args) throws IOException {
            ServerSocket serverSocket=null;
            try {
                serverSocket=new ServerSocket(8888);
                Socket socket=null;
                while(true){
                    socket=serverSocket.accept();
                    new Thread(new TimeServerHandler(socket)).start();
                }
            }finally {
                if(serverSocket!=null){
                    serverSocket.close();
                }
            }
        }
    }
    
    

    服务端处理器:

    package com.bj58.wuxian.bio;
    
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.Socket;
    
    public class TimeServerHandler implements Runnable{
        Socket socket;
    
        public TimeServerHandler(Socket socket) {
            super();
            this.socket = socket;
        }
    
        @Override
        public void run() {
            BufferedReader bufferedReader=null;
            String info=null;
            String currentTime = null;
            BufferedWriter bufferedWriter=null;
            try {
                bufferedReader=new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
                bufferedWriter=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8"));
                while (true) {
                    info=bufferedReader.readLine();
                    if(info==null){
                        break;
                    }
                    System.out.println("request:"+info);
                    currentTime = "QUERY TIME ORDER".equalsIgnoreCase(info) ? new java.util.Date(
                            System.currentTimeMillis()).toString() : "BAD ORDER";
                    bufferedWriter.write(currentTime+"\r\n");
                    bufferedWriter.flush();
                }
    
                
            } catch (IOException e) {
                 if (bufferedReader != null) {
                        try {
                            bufferedReader.close();
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                        }
                        if (bufferedWriter != null) {
                            try {
                                bufferedWriter.close();
                            } catch (IOException e1) {
                                e1.printStackTrace();
                            }
                            bufferedWriter = null;
                        }
                        if (this.socket != null) {
                        try {
                            this.socket.close();
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                        this.socket = null;
                        }
            }
        }   
    }
    
    

    客户端:

    package com.bj58.wuxian.bio;
    
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.Socket;
    
    public class TimeClient {
        public static void main(String[] args) {
            Socket socket = null;
            BufferedReader bufferedReader=null;
            BufferedWriter bufferedWriter=null;
            try {
                socket = new Socket("127.0.0.1", 8888);
                bufferedReader=new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
                bufferedWriter=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8"));
                bufferedWriter.write("QUERY TIME ORDER"+"\r\n");
                bufferedWriter.flush();
                String resp=bufferedReader.readLine();
                System.out.println("Now is:"+resp);
            
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if (bufferedWriter != null) {
                    try {
                        bufferedWriter.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    bufferedWriter = null;
                    }
    
                    if (bufferedReader != null) {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    bufferedReader = null;
                    }
                    if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    socket = null;
                    }
            }
        }
    }
    
    
    1.3.2 伪异步IO模型

    为了解决同步阻塞的一个线程一个连接的弊端,可以对他进行优化,即采用线程池和任务队列可以实现一种伪异步的IO。

    示例代码如下:
    server端运用线程池:

    package com.bj58.wuxian.pio;
    
    import java.io.IOException;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    import com.bj58.wuxian.bio.TimeServerHandler;
    
    public class TimeServer {
    
        public static void main(String[] args) throws IOException {
        ServerSocket server = null;
        try {
            server = new ServerSocket(8888);
            Socket socket = null;
            TimeServerHandlerExecutePool singleExecutor = new TimeServerHandlerExecutePool(
                50, 10000);
            while (true) {
            socket = server.accept();
            singleExecutor.execute(new TimeServerHandler(socket));
            }
        } finally {
            if (server != null) {
            System.out.println("The time server close");
            server.close();
            server = null;
            }
        }
        }
    }
    

    线程池:

    package com.bj58.wuxian.pio;
    
    import java.util.concurrent.ArrayBlockingQueue;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.ThreadPoolExecutor;
    import java.util.concurrent.TimeUnit;
    
    public class TimeServerHandlerExecutePool {
    
        private ExecutorService executor;
    
        public TimeServerHandlerExecutePool(int maxPoolSize, int queueSize) {
        executor = new ThreadPoolExecutor(Runtime.getRuntime()
            .availableProcessors(), maxPoolSize, 120L, TimeUnit.SECONDS,
            new ArrayBlockingQueue<java.lang.Runnable>(queueSize));
        }
        public void execute(java.lang.Runnable task) {
        executor.execute(task);
        }
    }
    
    
    1.3.3 NIO模型

    NIO是在JDK1.4引入的,它弥补了BIO的不足,NIO和BIO之间的最大的区别是,IO是面向流的,NIO是面向缓冲区的。它在标准的java代码中提供了高速度的、面向块(即缓冲区)的IO。NIO主要有三大核心部分:Channel(通道),Buffer(缓冲区), Selector(多路复用器)。 下面我们了解一下NIO的类库中的一些相关概念。

    1.3.3.1 Channel(通道):

    Channel是一个通道并且是双向的,可以通过它读取和写入数据。主要有以下:
    FileChannel:操作文件的Channel
    SocketChannel:操作Socket客户端的Channel
    ServerSocketChannel:操作Socket服务端的Channel
    DatagramChannel: 操作UDP的Channel

    1.3.3.2 Buffer(缓冲区):

    Buffer顾名思义,它是一个缓冲区,实际上是一个容器,一个连续数组,它包括了一些要写入或者要读出的数据。在NIO中所有的数据都是用缓冲区来处理的。任何时候访问NIO中的数据,都是通过缓冲区进行操作的。

    • capacity:作为一个内存块,Buffer有固定的容量,即“capacity”。一旦Buffer满了,需要将其清空(通过读数据或者清楚数据)才能继续写数据。
    • position:当你写数据到Buffer中时,position表示当前的位置。初始值为0,当写入数据时,position会向前移动到下一个可插入数据的Buffer单元。position最大可为capacity-1。当读取数据时,也是从某个特定位置读,将Buffer从写模式切换到读模式,position会被重置为0。当从Buffer的position处读取一个字节数据后,position向前移动到下一个可读的位置。
    • limit:在写模式下,Buffer的limit表示你最多能往Buffer里写多少数据。 写模式下,limit等于Buffer的capacity。当切换Buffer到读模式时, limit表示你最多能读到多少数据。因此,当切换Buffer到读模式时,limit会被设置成写模式下的position值。换句话说,你能读到之前写入的所有数据(limit被设置成已写数据的数量,这个值在写模式下就是position)

    Buffer的分配:对Buffer对象的操作必须首先进行分配,Buffer提供一个allocate(int capacity)方法分配一个指定字节大小的对象。

    向Buffer中写数据:写数据到Buffer中有两种方式:

    • 从channel写到Buffer
    int bytes = channel.read(buf); //将channel中的数据读取到buf中
    
    • 通过Buffer的put()方法写到Buffer
    buf.put(byte); //将数据通过put()方法写入到buf中
    
    • flip()方法:将Buffer从写模式切换到读模式,调用flip()方法会将position设置为0,并将limit设置为之前的position的值。

    从Buffer中读数据:从Buffer中读数据有两种方式:

    • 从Buffer读取数据到Channel
        int bytes = channel.write(buf); //将buf中的数据读取到channel中
    
    • 通过Buffer的get()方法读取数据
         byte bt = buf.get(); //从buf中读取一个byte
    
    • rewind()方法:Buffer.rewind()方法将position设置为0,使得可以重读Buffer中的所有数据,limit保持不变。
      Buffer中的数据,读取完成后,依然保存在Buffer中,可以重复读取。

    • clear()与compact()方法:一旦读完Buffer中的数据,需要让Buffer准备好再次被写入,可以通过clear()或compact()方法完成。如果调用的是clear()方法,position将被设置为0,limit设置为capacity的值。但是Buffer并未被清空,只是通过这些标记告诉我们可以从哪里开始往Buffer中写入多少数据。如果Buffer中还有一些未读的数据,调用clear()方法将被"遗忘 "。compact()方法将所有未读的数据拷贝到Buffer起始处,然后将position设置到最后一个未读元素的后面,limit属性依然设置为capacity。可以使得Buffer中的未读数据还可以在后续中被使用。

    • mark()与reset()方法:通过调用Buffer.mark()方法可以标记一个特定的position,之后可以通过调用Buffer.reset()恢复到这个position上。

    每一个Java基本类型(除了Boolean类型外)都对应一种缓冲区:ByteBuffer,CharBuffer,ShortBuffer,IntBuffer,LongBuffer,FloatBuffer,DoubleBuffer。

    1.3.3.3 Selector(多路复用器)

    多路选择器提供选择已经就绪的任务的能力。Selector不断的轮询注册在其上的Channel,如果某个Channel上面有新的TCP连接接入、读和写事件,这个Channel就处于就绪状态,会被Selector轮询出来,然后通过SelectionKey可以获取就绪的Channel集合,Selector可以监听状态有:Connect、Accept、Read、Write,当监听到某一Channel的某个状态时,才允许对Channel进行相应的操作。

    • Connect:某一个客户端连接成功后
    • Accept:准备好进行连接
    • Read:可读
    • Write:可写

    NIO时间服务实例:

    package com.bj58.wuxian.nio;
    
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.ServerSocketChannel;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    import java.util.Set;
    
    public class MultiplexerTimeServer implements Runnable {
        private Selector selector;
        private ServerSocketChannel serverSocketChannel;
        private volatile boolean stop;
    
        public MultiplexerTimeServer(int port) {
            try {
                selector = Selector.open();
                serverSocketChannel = ServerSocketChannel.open();
                serverSocketChannel.configureBlocking(false);
                serverSocketChannel.socket().bind(new InetSocketAddress(port), 1024);
                serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
                System.out.println("********start*******");
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(1);
            }
        }
    
        @Override
        public void run() {
            while (!stop) {
                try {
                    selector.select(1000);
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    SelectionKey key = null;
                    while (iterator.hasNext()) {
                        key = iterator.next();
                        iterator.remove();
                        try {
                            handleInput(key);
                        } catch (Exception e) {
                            if (key != null) {
                                key.cancel();
                                if (key.channel() != null)
                                    key.channel().close();
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
        private void handleInput(SelectionKey key) throws IOException {
            if (key.isValid()) {
                if (key.isAcceptable()) {
                    // 得到一个连接
                    ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    // 把连接注册到选择器上
                    sc.register(selector, SelectionKey.OP_READ);
                }
                if (key.isReadable()) {
                    SocketChannel sc = (SocketChannel) key.channel();
                    ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                    int readBytes = sc.read(readBuffer);
                    if (readBytes > 0) {
                        readBuffer.flip();
                        byte[] bytes = new byte[readBuffer.remaining()];
                        readBuffer.get(bytes);
                        String body = new String(bytes, "utf-8");
                        System.out.println("The time server receive order : " + body);
                        String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body)
                                ? new java.util.Date(System.currentTimeMillis()).toString() : "BAD ORDER";
                        doWrite(sc, currentTime);
                    } else if (readBytes < 0) {
                        // 对端链路关闭
                        key.cancel();
                        sc.close();
                    } else {
                        ;// 读到0字节,忽略
                    }
                }
            }
        }
    
        private void doWrite(SocketChannel sc, String response) throws IOException {
            if (response != null && response.trim().length() > 0) {
                byte[] bytes = response.getBytes();
                ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
                buffer.put(bytes);
                buffer.flip();
                sc.write(buffer);
            }
        }
        public void stop() {
            this.stop = true;
        }
    
    }
    
    package com.bj58.wuxian.nio;
    public class TimeServer {
        public static void main(String[] args) {
            MultiplexerTimeServer timeServer= new MultiplexerTimeServer(8888);
            new Thread(timeServer, "NIO-MultiplexerTimeServer-001").start();
        }
    }
    

    客户端处理器:

    package com.bj58.wuxian.nio;
    
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.ByteBuffer;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.util.Iterator;
    import java.util.Set;
    
    public class TimeClientHandle implements Runnable {
    
        private String host;
        private int port;
        private Selector selector;
        private SocketChannel socketChannel;
        private volatile boolean stop;
        
        public TimeClientHandle(String host, int port) {
            this.host = host;
            this.port = port;
            try {
                selector=Selector.open();
                socketChannel=SocketChannel.open();
                socketChannel.configureBlocking(false);
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(1);
            }
        }
    
        @Override
        public void run() {
            try {
                doConnect();
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(1);
            }
            while(!stop){
                try {
                    selector.select(1000);
                    Set<SelectionKey> selectionKeys =selector.selectedKeys();
                    Iterator<SelectionKey> iterator=selectionKeys.iterator();
                    SelectionKey key=null;
                    while(iterator.hasNext()){
                        key=iterator.next();
                        iterator.remove();
                        try{
                            handleInput(key);
                        }catch (Exception e) {
                            if (key != null) {
                                key.cancel();
                                if (key.channel() != null)
                                key.channel().close();
                            }
                            }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    System.exit(1);
                }
                
            }
        }
    
        private void handleInput(SelectionKey key) throws IOException {
            if (key.isValid()) {
                // 判断是否连接成功
                SocketChannel sc = (SocketChannel) key.channel();
                if (key.isConnectable()) {
                if (sc.finishConnect()) {
                    sc.register(selector, SelectionKey.OP_READ);
                    doWrite(sc);
                } else
                    System.exit(1);// 连接失败,进程退出
                }
                if (key.isReadable()) {
                ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                int readBytes = sc.read(readBuffer);
                if (readBytes > 0) {
                    readBuffer.flip();
                    byte[] bytes = new byte[readBuffer.remaining()];
                    readBuffer.get(bytes);
                    String body = new String(bytes, "UTF-8");
                    System.out.println("Now is : " + body);
                    this.stop = true;
                } else if (readBytes < 0) {
                    // 对端链路关闭
                    key.cancel();
                    sc.close();
                } else
                    ; // 读到0字节,忽略
                }
            }
        }
    
        private void doConnect() throws IOException {
            // 如果直接连接成功,则注册到多路复用器上,发送请求消息,读应答
            if(socketChannel.connect(new InetSocketAddress(host, port))){
                socketChannel.register(selector, SelectionKey.OP_READ);
                doWrite(socketChannel);
            }else{
                socketChannel.register(selector, SelectionKey.OP_CONNECT);
            }
            
        }
    
        private void doWrite(SocketChannel socketChannel) throws IOException {
            byte[] req = "QUERY TIME ORDER".getBytes();
            ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
            writeBuffer.put(req);
            writeBuffer.flip();
            socketChannel.write(writeBuffer);
            if (!writeBuffer.hasRemaining())
                System.out.println("Send order 2 server succeed.");
            }   
        }
    
    
    package com.bj58.wuxian.nio;
    
    public class TimeClient {
        public static void main(String[] args) {
        new Thread(new TimeClientHandle("127.0.0.1", 8888), "TimeClient-001")
            .start();
        }
    }
    

    是不是感觉很繁琐,哈哈哈~~~~~~

    1.3.4 AIO 模型

    NIO2.0引入了新的异步通道的概念,并提供了异步文件通道和异步套接字通道的实现。异步通道提供两种方式获取操作结果。

    • 通过java.util.concurrent.Future类来表示异步操作的结果
    • 在执行异步操作的时候传入一个java.nio.channels.Channel
      java.nio.channels.CompletionHandler接口的实现类作为操作完成的回调。
      NIO2.0的异步套接字通道是真正的异步非阻塞IO,它不需要通过多路复用器(Selector)对注册的通道进行轮询操作即可实现异步读写,从而简化了NIO的变成模型。
      其实也不简单,哈哈哈~~~~~
      实例如下:
      Server端:
    package com.bj58.wuxian.aio;
    
    import java.io.IOException;
    
    
    public class TimeServer {
        public static void main(String[] args) throws IOException {
        AsyncTimeServerHandler timeServer = new AsyncTimeServerHandler(8888);
        new Thread(timeServer, "AIO-AsyncTimeServerHandler-001").start();
        }
    }
    

    异步时间服务器的处理类:

    package com.bj58.wuxian.aio;
    
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.nio.channels.AsynchronousServerSocketChannel;
    import java.util.concurrent.CountDownLatch;
    
    public 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 e) {
                e.printStackTrace();
            }
        }
        @Override
        public void run() {
            latch=new CountDownLatch(1);
            doAccept();
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        private void doAccept() {
            asynchronousServerSocketChannel.accept(this,new AcceptCompletionHandler());
        }
    }
    
    
    package com.bj58.wuxian.aio;
    
    import java.nio.ByteBuffer;
    import java.nio.channels.AsynchronousSocketChannel;
    import java.nio.channels.CompletionHandler;
    
    public class AcceptCompletionHandler implements CompletionHandler<AsynchronousSocketChannel, AsyncTimeServerHandler> {
    
        @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));
        }
    
        @Override
        public void failed(Throwable exc, AsyncTimeServerHandler attachment) {
            exc.printStackTrace();
            attachment.latch.countDown();
        }
    }
    
    

    客户端:

    package com.bj58.wuxian.aio;
    
    import java.io.IOException;
    public class TimeServer {
        public static void main(String[] args) throws IOException {
        AsyncTimeServerHandler timeServer = new AsyncTimeServerHandler(8888);
        new Thread(timeServer, "AIO-AsyncTimeServerHandler-001").start();
        }
    }
    
    package com.bj58.wuxian.aio;
    
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    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 AsyncTimeClientHandler implements CompletionHandler<Void, AsyncTimeClientHandler>, Runnable {
    
        private AsynchronousSocketChannel client;
        private String host;
        private int port;
        private CountDownLatch latch;
    
        public AsyncTimeClientHandler(String host, int port) {
            this.host = host;
            this.port = port;
            try {
                client = AsynchronousSocketChannel.open();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        @Override
        public void run() {
            latch = new CountDownLatch(1);
            client.connect(new InetSocketAddress(host, port), this, this);
            try {
                latch.await();
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        @Override
        public void completed(Void result, AsyncTimeClientHandler attachment) {
            byte[] req = "QUERY TIME ORDER".getBytes();
            ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
            writeBuffer.put(req);
            writeBuffer.flip();
            client.write(writeBuffer, writeBuffer, new CompletionHandler<Integer, ByteBuffer>() {
                @Override
                public void completed(Integer result, ByteBuffer buffer) {
                    if (buffer.hasRemaining()) {
                        client.write(buffer, buffer, this);
                    } else {
                        ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                        client.read(readBuffer, readBuffer, new CompletionHandler<Integer, ByteBuffer>() {
                            @Override
                            public void completed(Integer result, ByteBuffer buffer) {
                                buffer.flip();
                                byte[] bytes = new byte[buffer.remaining()];
                                buffer.get(bytes);
                                String body;
                                try {
                                    body = new String(bytes, "UTF-8");
                                    System.out.println("Now is : " + body);
                                    latch.countDown();
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }
                            }
    
                            @Override
                            public void failed(Throwable exc, ByteBuffer attachment) {
                                try {
                                    client.close();
                                    latch.countDown();
                                } catch (IOException e) {
                                    // ingnore on close
                                }
                            }
                        });
                    }
                }
    
                @Override
                public void failed(Throwable exc, ByteBuffer attachment) {
                    try {
                        client.close();
                        latch.countDown();
                    } catch (IOException e) {
                        // ingnore on close
                    }
                }
            });
        }
    
        @Override
        public void failed(Throwable exc, AsyncTimeClientHandler attachment) {
            exc.printStackTrace();
            try {
                client.close();
                latch.countDown();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    package com.bj58.wuxian.aio;
    
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.nio.ByteBuffer;
    import java.nio.channels.AsynchronousSocketChannel;
    import java.nio.channels.CompletionHandler;
    
    public class ReadCompletionHandler implements CompletionHandler<Integer, ByteBuffer>  {
        private AsynchronousSocketChannel channel;
        public ReadCompletionHandler(AsynchronousSocketChannel channel) {
        if (this.channel == null)
            this.channel = channel;
        }
    
        @Override
        public void completed(Integer result, ByteBuffer attachment) {
            attachment.flip();
            byte[] body=new byte[attachment.remaining()];
            attachment.get(body);
            
            String req;
            try {
                req = new String(body,"utf-8");
                  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 (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
    
            
        }
    
        private void doWrite(String currentTime) {
            if(currentTime!=null&& currentTime.trim().length()>0){
                byte[] bytes=currentTime.getBytes();
                ByteBuffer writeBuffer=ByteBuffer.allocate(bytes.length);
                writeBuffer.put(bytes);
                writeBuffer.flip();
                channel.write(writeBuffer, writeBuffer, new CompletionHandler<Integer, ByteBuffer>() {
    
                    @Override
                    public void completed(Integer result, ByteBuffer attachment) {
                           // 如果没有发送完成,继续发送
                        if (attachment.hasRemaining())
                        channel.write(attachment, attachment, this);
                    }
    
                    @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();
            }
        }
    }
    
    

    我靠,是不是太麻烦了,用netty的话会简单很多,哈哈~~~~

    相关文章

      网友评论

          本文标题:第一讲 netty 基础与简介

          本文链接:https://www.haomeiwen.com/subject/zlphkftx.html