Java Nio 学习


1、前言

Java NIO提供了与标准IO不同的IO工作方式:

Channels and Buffers(通道和缓冲区):标准的IO基于字节流和字符流进行操作的,而NIO是基于通道(Channel)和缓冲区(Buffer)进行操作,数据总是从通道读取到缓冲区中,或者从缓冲区写入到通道中。

Asynchronous IO(异步IO):Java NIO可以让你异步的使用IO,例如:当线程从通道读取数据到缓冲区时,线程还是可以进行其他事情。当数据被写入到缓冲区时,线程可以继续处理它。从缓冲区写入通道也类似。

Selectors(选择器):Java NIO引入了选择器的概念,选择器用于监听多个通道的事件(比如:连接打开,数据到达)。因此,单个的线程可以监听多个数据通道。

Java NIO 核心部分:Channels、Buffers、Selectors。下面分别对其进行阐述。


2、Channels

A、简介

Java NIO的通道类似流,但又有些不同,它里面的通道是双向的:

  • 既可以从通道中读取数据,又可以写数据到通道。但流的读写通常是单向的。
  • 通道可以异步地读写。
  • 通道中的数据总是要先读到一个Buffer,或者总是要从一个Buffer中写入。
Channel —> Buffer

Buffer —> Channel

B、Channel的实现

Java NIO中最重要的通道的实现:

  • FileChannel:从文件中读写数据。
  • DatagramChannel:能通过UDP读写网络中的数据。
  • SocketChannel:能通过TCP读写网络中的数据。
  • ServerSocketChannel:可以监听新进来的TCP连接,像Web服务器那样。对每一个新进来的连接都会创建一个SocketChannel。

C、FileChannel示例

package nio.channel;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannelDemo {
    public static void main(String[] args) throws IOException {
        RandomAccessFile randomAccessFile = new RandomAccessFile("/Users/liqqc/Desktop/pid.txt", "rw");
        FileChannel fileChannel = randomAccessFile.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(48);
        int bytesRead = fileChannel.read(byteBuffer);
        while (bytesRead != -1) {
            System.out.println("Read " + bytesRead);
            byteBuffer.flip();
            while (byteBuffer.hasRemaining()) {
                System.out.print((char) byteBuffer.get());
            }
            byteBuffer.clear();
            bytesRead = fileChannel.read(byteBuffer);
        }
        randomAccessFile.close();
    }
}

3、Buffers

A、简介

Java NIO中的Buffer用于和NIO通道进行交互。数据是从通道读入缓冲区,从缓冲区写入到通道中的。

缓冲区本质上是一块可以写入数据,可以从中读取数据的内存。这块内存被包装成NIO Buffer对象,并提供了一组方法,用来方便的访问该块内存。


B、Buffer的基本用法

(1)使用Buffer读写数据一般遵循以下四个步骤:

  • 写入数据到Buffer
  • 调用flip()方法
  • 从Buffer中读取数据
  • 调用clear()方法或者compact()方法

当向buffer写入数据时,buffer会记录下写了多少数据。一旦要读取数据,需要通过flip()方法将Buffer从写模式切换到读模式。在读模式下,可以读取之前写入到buffer的所有数据。

一旦读完了所有的数据,就需要清空缓冲区,让它可以再次被写入。有两种方式能清空缓冲区:调用clear()或compact()方法。clear()方法会清空整个缓冲区。compact()方法只会清除已经读过的数据。任何未读的数据都被移到缓冲区的起始处,新写入的数据将放到缓冲区未读数据的后面。

(2)capacity,position、limit

缓冲区本质上是一块可以写入数据,然后可以从中读取数据的内存。这块内存被包装成NIO Buffer对象,并提供了一组方法,用来方便的访问该块内存。

为了理解Buffer的工作原理,需要熟悉它的三个属性:

  • capacity
  • position
  • limit

position和limit的含义取决于Buffer处在读模式还是写模式。不管Buffer处在什么模式,capacity的含义总是一样的。 作为一个内存块,Buffer有一个固定的大小值,也叫“capacity”。你只能往里写capacity个byte、long,char等类型。一旦Buffer满了,需要将其清空(通过读数据或者清除数据)才能继续写数据往里写数据。

当你写数据到Buffer中时,position表示当前的位置。初始的position值为0。当一个byte、long等数据写到Buffer后, position会向前移动到下一个可插入数据的Buffer单元。position最大可为capacity–1。

当读取数据时,也是从某个特定位置读。当将Buffer从写模式切换到读模式,position会被重置为0。当从Buffer的position处读取数据时,position向前移动到下一个可读的位置。

在写模式下,Buffer的limit表示你最多能往Buffer里写多少数据。 写模式下,limit等于Buffer的capacity。当切换Buffer到读模式时, limit表示你最多能读到多少数据。因此,当切换Buffer到读模式时,limit会被设置成写模式下的position值。换句话说,你能读到之前写入的所有数据(limit被设置成已写数据的数量,这个值在写模式下就是position)


C、Buffer类型和常用方法

(1)Java NIO 有以下Buffer类型:

  • ByteBuffer
  • MappedByteBuffer
  • CharBuffer
  • DoubleBuffer
  • FloatBuffer
  • IntBuffer
  • LongBuffer
  • ShortBuffer

这些Buffer类型代表了不同的数据类型。可以通过char,short,int,long,float 或 double类型来操作缓冲区中的字节。

(2)Buffer的分配

要想获得一个Buffer对象首先要进行分配。 每一个Buffer类都有一个allocate方法。下面是一个分配48字节capacity的ByteBuffer的例子。

ByteBuffer buffer = ByteBuffer.allocate(48);  

这是分配一个可存储1024个字符的CharBuffer:

CharBuffer buffer = CharBuffer.allocate(1024);  

(3)向Buffer中写数据

写数据到Buffer有两种方式:

  • 从Channel写到Buffer。
  • 通过Buffer的put()方法写到Buffer里。

从Channel写到Buffer的例子

int bytesRead = inChannel.read(buf); //read into buffer.  

通过put方法写Buffer的例子:

buf.put(127);  

put方法有很多版本,允许你以不同的方式把数据写入到Buffer中。例如, 写到一个指定的位置,或者把一个字节数组写入到Buffer。

(4)flip方法

flip方法将Buffer从写模式切换到读模式,position现在用于标记读的位置,limit表示之前写进了多少个byte、char等, 能读取多少个byte、char等。

(5)从Buffer中读取数据

  • 从Buffer读取数据到Channel。
  • 使用get()方法从Buffer中读取数据。

从Buffer读取数据到Channel示例:

//read from buffer into channel.  
int bytesWritten = inChannel.write(buf);  

get方法允许你以不同的方式从Buffer中读取数据。例如,从指定position读取,或者从Buffer中读取数据到字节数组,从Buffer中读取数据示例:

byte aByte = buf.get();  

(6)rewind方法

rewind方法将position设回0,你可以重读Buffer中的所有数据,limit保持不变,其表示能从Buffer中读取多少个元素(byte、char等)。

(7)clear、compact方法

一旦读完Buffer中的数据,需要让Buffer准备好再次被写入,可以通过clear()或compact()方法来完成。

如果调用的是clear()方法,position将被设回0,limit被设置成 capacity的值,即Buffer 被清空了。Buffer中的数据并未清除,只是这些标记告诉我们可以从哪里开始往Buffer里写数据。

如果Buffer中有一些未读的数据,调用clear()方法,数据将“被遗忘”,意味着不再有任何标记会告诉你哪些数据被读过,哪些还没有。

如果Buffer中仍有未读的数据,且后续还需要这些数据,但此时要先写数据,可以使用compact()方法。compact()方法将所有未读的数据拷贝到Buffer起始处,然后将position设到最后一个未读元素的后面。这样,Buffer准备好写数据了,但是不会覆盖未读的数据。

(8)mark、reset方法

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

buffer.mark();  

//call buffer.get() a couple of times, e.g. during parsing.  

buffer.reset();  //set position back to mark.  

D、代码示例

package nio.buffer;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;

public class BufferDemo {
    public static void main(String[] args) {
        //分配空间 隐含地在内存中分配了一个byte型数组来存储20个byte
        ByteBuffer byteBuffer = ByteBuffer.allocate(20);

        //填充元素 buffer.hasRemaining()用于判断缓冲区是否达到上界limit
        int i = 0;
        while (byteBuffer.hasRemaining()) {
            byteBuffer.put((byte) i++);
        }

        //翻转缓冲区 将缓冲区进行翻转操作,即在缓冲区写入完毕时,将缓冲区翻转成一个准备读出元素的状态
        byteBuffer.flip();

        //读取缓冲区
        int remainCount = byteBuffer.remaining();
        for (int j = 0; j < remainCount; j++) {
            System.out.print(byteBuffer.get() + " ");
            //byteBuffer.clear(); 清除整个缓冲区数据
            //byteBuffer.compact(); 清除已读的缓冲区数据
        }

        System.out.println();
        System.out.println();

        // 字节顺序
        System.out.println("ByteOrder的字节顺序为:" + ByteOrder.nativeOrder());
        System.out.println("ByteBuffer的字节顺序为:" + byteBuffer.order());
        CharBuffer charBuffer = CharBuffer.allocate(20);
        System.out.println("CharBuffer的字节顺序为:" + charBuffer.order());
        // 修改ButyBuffer的字节顺序
        byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
        System.out.println("ByteBuffer的字节顺序为:" + byteBuffer.order());

        //只有ByteBuffer可以创建直接缓冲区,用wrap函数创建的缓冲区都是非直接的缓冲区
        ByteBuffer redirectByteBuffer = ByteBuffer.allocateDirect(10);
        System.out.println("判断缓冲区是否为直接缓冲区:" + redirectByteBuffer.isDirect());

        System.out.println();

        // 先创建一个大端字节顺序的ByteBuffer,然后再创建一个字符视图缓冲区
        ByteBuffer bigByteBuffer = ByteBuffer.allocate(50).order(ByteOrder.BIG_ENDIAN);
        CharBuffer viewCharBuffer = bigByteBuffer.asCharBuffer();
        viewCharBuffer.put("how do you do ?");
        //在字符视图的基础上创建只读字符视图,只能读而不能写,否则抛出ReadOnlyBufferException
        CharBuffer onlyReadCharBuffer = viewCharBuffer.asReadOnlyBuffer();
//        onlyReadCharBuffer.put("aaa");   Exception in thread "main" java.nio.ReadOnlyBufferException
//        System.err.println(onlyReadCharBuffer.get(1));


        viewCharBuffer.flip();
        System.out.println("asCharBuffer()--->position=" + viewCharBuffer.position() + ",limit=" + viewCharBuffer.limit());
        while (viewCharBuffer.hasRemaining()) {
            System.out.print((char) viewCharBuffer.get());
        }

        System.out.println();
        System.out.println();
        System.out.println();

        //创建一个与原始缓冲区相似的新缓冲区,两个缓冲区共享数据元素,拥有同样的容量,但每个缓冲区拥有各自的位置、上界、标记属性。 对一个缓冲区的数据元素所做的改变会反映在另一个缓冲区上,新的缓冲区会继承原始缓冲区的这些属性。
        CharBuffer copyCharBuffer = viewCharBuffer.duplicate();
        System.out.println("duplicate()--->position=" + copyCharBuffer.position() + ",limit=" + copyCharBuffer.limit());
        copyCharBuffer.position(2);
        while (copyCharBuffer.hasRemaining()) {
            System.out.print((char) copyCharBuffer.get());
        }

        System.out.println();
        System.out.println();
        System.out.println();

        //创建原始缓冲区子集的新缓冲区,新缓冲区的内容将从该缓冲区的当前位置开始。对这个缓冲区的内容做出的改变将在反映在新的缓冲区上,可见,反之亦然;这两个缓冲区的位置、限制和标记值将是独立的。
        viewCharBuffer.position(1);
        CharBuffer cutCharBuffer = viewCharBuffer.slice();
        System.out.println("slice()--->position=" + cutCharBuffer.position() + ",limit=" + cutCharBuffer.limit()+",capacity="+cutCharBuffer.capacity());
        while (cutCharBuffer.hasRemaining()) {
            System.out.print((char) cutCharBuffer.get());
        }
        System.out.println();
        System.out.println();
        System.out.println();

    }
}

4、Selectors

Selector(选择器)是Java NIO中能够检测一到多个NIO通道,并能够知晓通道是否为诸如读写事件做好准备的组件。这样,一个单独的线程可以管理多个channel,从而管理多个网络连接。它能够检测一到多个NIO通道,并能够知晓通道是否为诸如读写事件做好准备的组件。这样,一个单独的线程可以管理多个channel,从而管理多个网络连接。

(1) 使用Selector的好处

仅用单个线程来处理多个Channels的好处是:只需要更少的线程来处理通道。我们完全可以只用一个线程处理所有的通道。对于操作系统来说,线程之间上下文切换的开销很大,而且每个线程都要占用系统的一些资源(如内存)。因此,使用的线程越少越好。

现代的操作系统和CPU在多任务方面表现的越来越好,多线程的开销随着时间的推移,将变得越来越小了。如果一个CPU有多个内核,不使用多任务可能是在浪费CPU能力。在这里,只要知道使用Selector能够处理多个通道就足够了。

(2) Selector的创建

通过调用Selector.open()方法创建一个Selector,如下:

Selector selector = Selector.open();  

(3) 向Selector注册通道

为了将Channel和Selector配合使用,必须将channel注册到selector上。通过SelectableChannel.register()方法来实现,如下:

channel.configureBlocking(false);  
SelectionKey key = channel.register(selector,  
    Selectionkey.OP_READ);  

Channel必须处于非阻塞模式下,才能与Selector一起使用时。这意味着不能将FileChannel与Selector一起使用,因为FileChannel不能切换到非阻塞模式,而套接字通道都可以。

在register()方法的第二个参是一个”interest集合”(The interest set for the resulting key),在通过Selector监听Channel时,可以自行选择对什么事件感兴趣。可以监听四种不同类型的事件:

  • Connect
  • Accept
  • Read
  • Write

通道触发了一个事件意味着该事件已经就绪,某个channel成功连接到另一个服务器称为”连接就绪”;而一个server socket channel准备好接收新进入的连接称为”接收就绪”;一个有数据可读的通道可以说是”读就绪”;而等待写数据的通道可以说是”写就绪”。

这四种事件用SelectionKey的四个常量来表示:

  • SelectionKey.OP_CONNECT
  • SelectionKey.OP_ACCEPT
  • SelectionKey.OP_READ
  • SelectionKey.OP_WRITE

如果对不止一种事件感兴趣,可以用“位或”操作符将常量连接起来,如下:

int interestSet = SelectionKey.OP_READ | SelectionKey.OP_WRITE;  

(4) SelectionKey

当向Selector注册Channel时,register()方法会返回一个SelectionKey对象,这个对象包含了一些你感兴趣的属性:

  • interest集合
  • ready集合
  • Channel
  • Selector

~ interest集合

interest集合是你所选择的感兴趣的事件集合,可以通过SelectionKey读写interest集合,如下代码所示:

可以看到,用“位与”操作interest 集合和给定的SelectionKey常量,可以确定某个确定的事件是否在interest 集合中。

int interestSet = selectionKey.interestOps();  

boolean isInterestedInAccept  = (interestSet & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT;  
boolean isInterestedInConnect = interestSet & SelectionKey.OP_CONNECT;  
boolean isInterestedInRead    = interestSet & SelectionKey.OP_READ;  
boolean isInterestedInWrite   = interestSet & SelectionKey.OP_WRITE; 

~ready集合

ready 集合是通道已经准备就绪的操作的集合。在一次Selection之后,会首先访问这个ready set,可以这样访问ready集合:

int readySet = selectionKey.readyOps(); 

可以用像检测interest集合那样的方法,来检测channel中什么事件或操作已经就绪。可以使用以下四个方法,它们都会返回一个布尔类型:

selectionKey.isAcceptable();  
selectionKey.isConnectable();  
selectionKey.isReadable();  
selectionKey.isWritable();  

从SelectionKey访问Channel和Selector很简单。如下:

Channel  channel  = selectionKey.channel();  
Selector selector = selectionKey.selector();  

可以将一个对象或者更多信息附着到SelectionKey上,这样就能方便的识别某个给定的通道。例如,可以附加与通道一起使用的Buffer,或是包含聚集数据的某个对象,使用方法如下:

selectionKey.attach(theObject);  
Object attachedObj = selectionKey.attachment(); 

还可以在用register()方法向Selector注册Channel的时候附加对象。如:

SelectionKey key = channel.register(selector, SelectionKey.OP_READ, theObject);  

(5) 通过Selector选择通道

一旦向Selector注册了一或多个通道,就可以调用几个重载的select()方法,这些方法返回你所感兴趣的事件(如连接、接受、读或写)对应的已经准备就绪的那些通道。如果你对“读就绪”的通道感兴趣,select()方法会返回读事件已经就绪的那些通道。 下面是select()方法:

  • int select()
  • int select(long timeout)
  • int selectNow()
  • select()

select(long timeout)和select()一样,除了最长会阻塞timeout毫秒(参数)。 selectNow()不会阻塞,不管什么通道就绪都立刻返回(此方法执行非阻塞的选择操作。如果自从前一次选择操作后,没有通道变成可选择的,则此方法直接返回零)。 select()方法返回的int值表示有多少通道已经就绪,自上次调用select()方法后有多少通道变成就绪状态。如果调用select()方法,因为有一个通道变成就绪状态,返回了1,若再次调用select()方法,如果另一个通道就绪了,它会再次返回1。如果对第一个就绪的channel没有做任何操作,现在就有两个就绪的通道,但在每次select()方法调用之间,只有一个通道就绪了。

一旦调用了select()方法,并且返回值表明有一个或更多个通道就绪了,然后可以通过调用selector的selectedKeys()方法,访问“已选择键集(selected key set)”中的就绪通道,如下所示:

Set selectedKeys = selector.selectedKeys();  

当像Selector注册Channel时,Channel.register()方法会返回一个SelectionKey 对象,这个对象代表了注册到该Selector的通道,可以通过SelectionKey的selectedKeySet()方法访问这些对象。如下展示遍历已选择键集合来访问就绪的通道:

Set selectedKeys = selector.selectedKeys();  
Iterator keyIterator = selectedKeys.iterator();  
while(keyIterator.hasNext()) {  
    SelectionKey key = keyIterator.next();  
    if(key.isAcceptable()) {  
        // a connection was accepted by a ServerSocketChannel.  
    } else if (key.isConnectable()) {  
        // a connection was established with a remote server.  
    } else if (key.isReadable()) {  
        // a channel is ready for reading  
    } else if (key.isWritable()) {  
        // a channel is ready for writing  
    }  
}  

这个循环遍历已选择键集中的每个键,并检测各个键所对应的通道的就绪事件。 注意:每次迭代末尾的keyIterator.remove()调用。因为Selector不会自己从已选择键集中移除SelectionKey实例,必须在处理完通道时自己移除。下次该通道变成就绪时,Selector会再次将其放入已选择键集中。

(6) wakeUp()

某个线程调用select()方法后阻塞了,即使没有通道已经就绪,也有办法让其从select()方法返回。只要让其它线程在第一个线程调用select()方法的那个对象上调用Selector.wakeup()方法即可,阻塞在select()方法上的线程会立马返回。 如果有其它线程调用了wakeup()方法,但当前没有线程阻塞在select()方法上,下个调用select()方法的线程会立即”醒来(wake up)”。

(7) close()

用完Selector后调用其close()方法会关闭该Selector,且使注册到该Selector上的所有SelectionKey实例无效,但通道本身并不会关闭。


5、 完整示例

下面是一个完整的客服端与服务器端通信代码示例。打开Selector,将通道注册到这个Selector上,监控Selector上的事件(接受,连接,读,写),收到事件后转发处理。

服务器端代码:

package nio.jnio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class Server implements Runnable {

    private Selector selector;
    private ServerSocketChannel serverSocketChannel;
    private int port;

    public Server(int port) {
        this.port = port;
        initServer();
    }

    public void initServer() {
        try {
            this.selector = Selector.open();
            this.serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.bind(new InetSocketAddress(port));
            SelectionKey selectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            selectionKey.attach(new Acceptor());
        } catch (ClosedChannelException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new Thread(new Server(8080)).start();
    }

    public void run() {
        while (true) {
            try {
                selector.select();
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey next = iterator.next();
                    iterator.remove();
                    if (!next.isValid()) {
                        continue;
                    }
                    dispatch(next);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void dispatch(SelectionKey next) {
        Runnable acceptor = (Runnable) next.attachment();
        if (acceptor != null) {
            acceptor.run();
        }
    }

    public class Acceptor implements Runnable {
        public void run() {
            try {
                accept();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private void accept() throws IOException {
        SocketChannel accept = serverSocketChannel.accept();
        accept.configureBlocking(false);
        new Handler(selector, accept);
    }

    public class Handler implements Runnable {
        private SocketChannel socketChannel;
        private SelectionKey key;
        static final int MAXIN = 8192, MAXOUT = 11240 * 1024;
        ByteBuffer readBuffer = ByteBuffer.allocate(MAXIN);
        ByteBuffer outBuffer = ByteBuffer.allocate(MAXOUT);
        static final int READING = 0;
        static final int SENDING = 1;
        int state = READING;

        public Handler(Selector selector, SocketChannel accept) {
            try {
                this.socketChannel = accept;
                this.key = accept.register(selector, SelectionKey.OP_READ);
                this.key.attach(this);
            } catch (ClosedChannelException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        private void write() throws IOException {
            socketChannel.write(outBuffer);
            if (outBuffer.remaining() > 0) {
                return;
            }
            state = READING;
            key.interestOps(SelectionKey.OP_READ);
        }

        private void read() throws IOException {
            readBuffer.clear();
            int numRead;
            try {
                // 读取数据
                numRead = socketChannel.read(readBuffer);
            } catch (Exception e) {
                key.cancel();
                socketChannel.close();
                return;
            }

            if (numRead == -1) {
                socketChannel.close();
                key.cancel();
                return;
            }
            // 处理数据
            process(numRead);
        }

        private void process(int numRead) {
            byte[] data = new byte[numRead];
            System.arraycopy(readBuffer.array(), 0, data, 0, numRead);
            System.err.println(new String(data));
            outBuffer = ByteBuffer.wrap(data);
            state = SENDING;
            key.interestOps(SelectionKey.OP_WRITE);
        }

        public void run() {
            try {
                if (state == READING) {
                    read();
                } else if (state == SENDING) {
                    write();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

客户端代码:

package nio.jnio;

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.nio.channels.spi.SelectorProvider;
import java.util.Iterator;

/**
 * 
 * @author liqqc
 *
 */
public class NioClient implements Runnable {
    private int port;
    private Selector selector;
    private ByteBuffer readBuffer = ByteBuffer.allocate(8192);
    private ByteBuffer outBuffer = ByteBuffer.wrap("how do you do".getBytes());

    public NioClient(int port) throws IOException {
        this.port = port;
        initSelector();
    }

    public static void main(String[] args) {
        try {
            new Thread(new NioClient(8080)).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true) {
            try {
                selector.select();

                Iterator<?> selectedKeys = selector.selectedKeys().iterator();
                while (selectedKeys.hasNext()) {
                    SelectionKey key = (SelectionKey) selectedKeys.next();
                    selectedKeys.remove();

                    if (!key.isValid()) {
                        continue;
                    }

                    if (key.isConnectable()) {
                        finishConnection(key);
                    } else if (key.isReadable()) {
                        read(key);
                    } else if (key.isWritable()) {
                        write(key);
                    }

                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    private void initSelector() throws IOException {
        // 创建一个selector
        selector = SelectorProvider.provider().openSelector();
        // 打开SocketChannel
        SocketChannel socketChannel = SocketChannel.open();
        // 设置为非阻塞
        socketChannel.configureBlocking(false);
        // 连接指定IP和端口的地址
        socketChannel.connect(new InetSocketAddress(this.port));
        // 用selector注册套接字,并返回对应的SelectionKey,同时设置Key的interest set为监听服务端已建立连接的事件
        socketChannel.register(selector, SelectionKey.OP_CONNECT);
    }

    private void finishConnection(SelectionKey key) throws IOException {
        SocketChannel socketChannel = (SocketChannel) key.channel();
        try {
            // 判断连接是否建立成功,不成功会抛异常
            socketChannel.finishConnect();
        } catch (IOException e) {
            key.cancel();
            return;
        }
        // 设置Key的interest set为OP_WRITE事件
        key.interestOps(SelectionKey.OP_WRITE);
    }

    /**
     * 处理read
     * @param key
     * @throws IOException
     */
    private void read(SelectionKey key) throws IOException {
        SocketChannel socketChannel = (SocketChannel) key.channel();
        readBuffer.clear();
        int numRead;
        try {
            numRead = socketChannel.read(readBuffer);
        } catch (Exception e) {
            key.cancel();
            socketChannel.close();
            return;
        }
        if (numRead == 1) {
            System.out.println("close connection");
            socketChannel.close();
            key.cancel();
            return;
        }
        // 处理响应
        handleResponse(socketChannel, readBuffer.array(), numRead);
    }

    /**
     * 处理响应
     * @param socketChannel
     * @param data
     * @param numRead
     * @throws IOException
     */
    private void handleResponse(SocketChannel socketChannel, byte[] data, int numRead) throws IOException {
        byte[] rspData = new byte[numRead];
        System.arraycopy(data, 0, rspData, 0, numRead);
        System.out.println(new String(rspData));
        socketChannel.close();
        socketChannel.keyFor(selector).cancel();
    }

    /**
     * 处理write
     * @param key
     * @throws IOException
     */
    private void write(SelectionKey key) throws IOException {
        SocketChannel socketChannel = (SocketChannel) key.channel();
        socketChannel.write(outBuffer);
        if (outBuffer.remaining() > 0) {
            return;
        }
        // 设置Key的interest set为OP_READ事件
        key.interestOps(SelectionKey.OP_READ);
    }

}

参考:
    http://www.iteye.com/magazines/132-Java-NIO
    http://ifeve.com/overview/

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值