NIO介绍~基于NIO的客户端与服务端

1. Java NIO 和 IO 之间的主要差别

IONIO
面向流面向缓冲
阻塞IO

非阻塞IO

选择器

    Java NIO 的选择器允许一个单独的线程来监视多个输入通道,你可以注册多个通道使用一个选择器,然后使用一个单独的线程来 "选择" 通道。

2. Java NIO 的通道类似流,但又有些不同

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

正如上面所说,从通道读取数据到缓冲区,从缓冲区写入数据到通道。Java NIO 中最重要的通道的实现:

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

3. 下面是一个使用 FileChannel 读取数据到 Buffer 中的示例

RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw");     
FileChannel inChannel = aFile.getChannel();  
ByteBuffer buf = ByteBuffer.allocate(48);//48个字节
int bytesRead = inChannel.read(buf);
while (bytesRead != -1) {
    System.out.println("Read " + bytesRead);
    buf.flip();
    while(buf.hasRemaining()){
        System.out.print((char) buf.get());
    }
    buf.clear();
    bytesRead = inChannel.read(buf);
}
aFile.close();

     注意 : buf.flip() 的调用,首先读取数据到 Buffer,然后反转 Buffer, 接着再从 Buffer 中读取数据。

     一旦读完了所有的数据,就需要清空缓冲区,让它可以再次被写入。

    有两种方式能清空缓冲区:调用 clear() 或 compact() 方法。clear() 方法会清空整个缓冲区。compact() 方法只会清除已经读过的数据。任何未读的数据都被移到缓冲区的起始处,新写入的数据将放到缓冲区未读数据的后面。

4. Scatter/Gather

Scattering Reads 是指数据从一个 channel 读取数据到多个 buffer 中。

ByteBuffer header = ByteBuffer.allocate(128);
ByteBuffer body   = ByteBuffer.allocate(1024);
ByteBuffer[] bufferArray = { header, body };
channel.read(bufferArray);

read() 方法按照 buffer 在数组中的顺序将从 channel 中读取的数据写入到 buffer,当一个 buffer 被写满后,channel 紧接着向另一个 buffer 中写。它不适用于消息大小不固定的动态消息。

Gathering Writes 是指数据从多个 buffer 写入到同一个 channel。

ByteBuffer header = ByteBuffer.allocate(128);
ByteBuffer body   = ByteBuffer.allocate(1024);
//write data into buffers
ByteBuffer[] bufferArray = { header, body };
channel.write(bufferArray);

write() 方法会按照 buffer 在数组中的顺序,将数据写入到 channel,与 Scattering Reads 相反,Gathering Writes 能较好的处理动态消息。

5. Java NIO 中,若两个通道中有一个是 FileChannel,那可直接将数据从一个 channel传输到另外一个 channel。

transferFrom() : 将数据从源通道传输到 FileChannel 中

transferTo() : 将数据从 FileChannel 传输到其他的 channel 中。

RandomAccessFile fromFile = new RandomAccessFile("fromFile.txt", "rw");
FileChannel fromChannel = fromFile.getChannel();
RandomAccessFile toFile = new RandomAccessFile("toFile.txt", "rw");
FileChannel toChannel = toFile.getChannel();
long position = 0;
long count = fromChannel.size();
toChannel.transferFrom(position, count, fromChannel);

注意:如果源通道的剩余空间小于 count 个字节,则所传输的字节数要小于请求的字节数。

6. Selector

     Java NIO 中能够检测一到多个 NIO 通道,并能够知晓通道是否为诸如读写事件做好准备的组件。这样,一个单独的线程(对于操作系统来说,线程之间上下文切换的开销很大)可以管理多个 channel,从而管理多个网络连接。FileChannel无法切换至非阻塞,而套接字通道都可以。

 

//创建selector
Selector selector = Selector.open(); 
//channel必须非阻塞模式(FileChannel无法切换至非阻塞)
channel.configureBlocking(false);
//通过Selector监听Channel的事件
SelectionKey key = channel.register(selector, Selectionkey.OP_READ);

四种事件:

  1. SelectionKey.OP_CONNECT
  2. SelectionKey.OP_ACCEPT
  3. SelectionKey.OP_READ
  4. SelectionKey.OP_WRITE

SelectionKey属性:

    interest 集合 //你所选择的感兴趣的事件集合

    ready 集合 //通道已经准备就绪的操作的集合

    Channel //selectionKey.channel();

    //SelectionKey.channel() 方法返回的通道需要转型成你要处理的类型,如 ServerSocketChannel/SocketChannel

    Selector //selectionKey.selector();

Selector 选择通道

    select() //阻塞到至少有一个通道在你注册的事件上就绪

    select(long timeout)

    selectNow() //不会阻塞

    当 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
    }
    //Selector 不会自己从已选择键集中移除 SelectionKey 实例。必须在处理完通道时自己移除。
    keyIterator.remove();
}

wakeUp()

某个线程调用 select() 方法后阻塞了,即使没有通道已经就绪,只要让其它线程在第一个线程调用 select() 方法的那个对象上调用 Selector.wakeup() 方法即可,阻塞在 select() 方法上的线程会立马返回。

close()

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

完整的示例

Selector selector = Selector.open();
channel.configureBlocking(false);
SelectionKey key = channel.register(selector, SelectionKey.OP_READ);
while(true) {
  int readyChannels = selector.select();
  if(readyChannels == 0) continue;
  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();
  }
}

7. FileChannel

Java NIO 中的 FileChannel 是一个连接到文件的通道,无法设置为非阻塞模式,它总是运行在阻塞模式下。

FileChannel.write() 方法向 FileChannel 写数据。因为无法保证 write() 方法一次能向 FileChannel 写入多少字节,因此需要重复调用 write() 方法,直到 Buffer 中已经没有尚未写入通道的字节。用完 FileChannel 后必须将其关闭。

String newData = "New String to write to file..." + System.currentTimeMillis();
ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes());
buf.flip();
while(buf.hasRemaining()) {
    channel.write(buf);
}

FileChannel.force() 方法将通道里尚未写入磁盘的数据强制写到磁盘上。出于性能方面的考虑,操作系统会将数据缓存在内存中,所以无法保证写入到 FileChannel 里的数据一定会即时写到磁盘上。要保证这一点,需要调用 force() 方法,它有一个 boolean 类型的参数,指明是否同时将文件元数据(权限信息等)写到磁盘上。

8. SocketChannel 

SocketChannel 是一个连接到 TCP 网络套接字的通道。读写与FileChannel类似。可以设置 SocketChannel 为非阻塞模式(non-blocking mode). 设置之后,就可以在异步模式下调用 connect(), read() 和 write() 了。

非阻塞模式下:

connect(),该方法可能在连接建立之前就返回了。

finishConnect() //为了确定连接是否建立

write() 方法在尚未写出任何内容时可能就返回了,所以需要在循环中调用 write()。

read() 方法在尚未读取到任何数据时可能就返回了。所以需要关注它的 int 返回值,它会告诉你读取了多少字节。

9. ServerSocketChannel

可以设置成非阻塞模式。在非阻塞模式下,accept() 方法会立刻返回,如果还没有新进来的连接,返回的将是 null。 因此,需要检查返回的 SocketChannel 是否是 null。

ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(9999));
serverSocketChannel.configureBlocking(false);
while(true){
    SocketChannel socketChannel =
            serverSocketChannel.accept();
    if(socketChannel != null){
        //do something with socketChannel...
    }
}

10. DatagramChannel

Java NIO 中的 DatagramChannel 是一个能收发 UDP 包的通道。 UDP 是无连接的网络协议。

接收数据:

DatagramChannel channel = DatagramChannel.open();
channel.socket().bind(new InetSocketAddress(9999));
ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
channel.receive(buf);//receive() 将接收到的数据包内容复制到指定的 Buffer. 若存在多出的数据则将被丢弃。

发送数据:(因为服务端并没有监控这个端口,所以什么也不会发生。也不会通知你发出的数据包是否已收到,因为 UDP 在数据传送方面没有任何保证。)

String newData = "New String to write to file..." + System.currentTimeMillis();
ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes());
buf.flip();
int bytesSent = channel.send(buf,
new InetSocketAddress("jenkov.com", 80));

11. Pipe

    Java NIO 管道是 2 个线程之间的单向数据连接。Pipe有一个 source 通道和一个 sink 通道。数据会被写到 sink 通道,从 source 通道读取。

 

Pipe pipe = Pipe.open();  //打开管道
Pipe.SinkChannel sinkChannel = pipe.sink();  //向管道写数据
String newData = "New String to write to file..." + System.currentTimeMillis();
ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();
buf.put(newData.getBytes());
buf.flip();
while(buf.hasRemaining()) {
    sinkChannel.write(buf);
}

读数据:

Pipe.SourceChannel sourceChannel = pipe.source();
ByteBuffer buf = ByteBuffer.allocate(48);
int bytesRead = sourceChannel.read(buf);  //read()方法返回的 int 值会告诉我们多少字节被读进了缓冲区

 

案例:基于NIO的客户端与服务端

NIO服务端

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
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;
/**
 * @describe: NIO 服务端
 * @author: houkai
 */
public class NIOServer {

    private Selector selector;

    public void init() throws IOException {
        // 创建一个选择器
        this.selector = Selector.open();
        // 打开一个服务器套接字通道
        ServerSocketChannel channel = ServerSocketChannel.open();
        // 设置通道为非阻塞模式
        channel.configureBlocking(false);
        ServerSocket serverSocket = channel.socket();
        InetSocketAddress address = new InetSocketAddress(9999);
        serverSocket.bind(address);
        // 注册事件
        channel.register(selector, SelectionKey.OP_ACCEPT);
    }

    public void start() throws IOException {
        while (true) {
            // 选择器运行
            this.selector.select();
            Iterator<SelectionKey> iterator = this.selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                //移除,防止重复操作
                iterator.remove();
                if (key.isAcceptable()) {
                    accept(key);
                } else if (key.isReadable()) {
                    read(key);
                }
            }
        }
    }

    private void accept(SelectionKey key) throws IOException {
        // 事件传过来的key
        ServerSocketChannel server = (ServerSocketChannel) key.channel();
        // 转成客户端的通道
        SocketChannel channel = server.accept();
        // 设置成非阻塞
        channel.configureBlocking(false);
        // 注册一个读事件
        channel.register(this.selector, SelectionKey.OP_READ);
    }

    private void read(SelectionKey key) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        SocketChannel channel = (SocketChannel) key.channel();
        //读取请求
        channel.read(buffer);
        String request = new String(buffer.array()).trim();
        String outString = "HTTP/1.1 200 OK\n" + "Content-Type: text/html;charset=UTF-8\n\n" + "NIOsuccess\n 请求的信息:" + request;
        ByteBuffer outBuffer = ByteBuffer.wrap(outString.getBytes());
        channel.write(outBuffer);
        channel.close();
    }

    public static void main(String[] args) throws Exception {
        NIOServer server = new NIOServer();
        server.init();
        server.start();
    }
}

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;

/**
 * @describe: nio 客户端
 * @author: houkai
 */
public class NIOClient {
    private static final String host = "127.0.0.1";
    private static final int port = 9999;
    private Selector selector;
    private SocketChannel socketChannel;
    private volatile boolean stop = false;

    private NIOClient() {
        try {
            selector = Selector.open();
            socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    public static void main(String[] args) throws IOException {
        NIOClient client = new NIOClient();
        client.start();
    }

    public void start()  throws IOException{
        //建立连接
        doConnect();

        //将服务器响应的数据读取完毕后退出
        while (!stop) {
            try {
                //阻塞等待1s,若超时则返回
                selector.select(1000);
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> it = selectionKeys.iterator();
                SelectionKey key = null;
                while (it.hasNext()) {
                    key = it.next();
                    //获取之后删除
                    it.remove();
                    try {
                        handleInput(key);
                    } catch (Exception e) {
                        if (key != null) {
                            //取消selectionkey
                            key.cancel();
                            if (key.channel() != null) {
                                //关闭该通道
                                key.channel().close();
                            }
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(1);
            }
        }

        if (selector != null) {
            try {
                selector.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void handleInput(SelectionKey key) throws IOException {
        //若该selectorkey可用
        if (key.isValid()) {
            //将key转型为SocketChannel
            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);
                System.out.println("before  :  " + readBuffer);
                //从管道中读取数据然后写入缓冲区中
                int readBytes = sc.read(readBuffer);
                System.out.println("after :  " + readBuffer);
                //若有数据
                if (readBytes > 0) {
                    //反转缓冲区
                    readBuffer.flip();
                    System.out.println(readBuffer);

                    byte[] bytes = new byte[readBuffer.remaining()];
                    //获取缓冲区并写入字节数组中
                    readBuffer.get(bytes);
                    //将字节数组转换为String类型
                    String body = new String(bytes);
                    System.out.println(body.length());
                    System.out.println("Now is : " + body + "!");
                    this.stop = true;
                } else if (readBytes < 0) {
                    key.cancel();
                    sc.close();
                } else {
                    sc.register(selector, SelectionKey.OP_READ);
                }
            }
        }
    }

    public void doConnect() throws IOException {
        //通过IP和端口号连接到服务器
        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 sc) throws IOException {
        //要写的内容
        byte[] req = "hello world".getBytes();
        //为字节缓冲区分配指定字节大小的容量
        ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
        //将内容写入缓冲区
        writeBuffer.put(req);
        //反转缓冲区
        writeBuffer.flip();
        //输出打印缓冲区的可读大小
        System.out.println(writeBuffer.remaining());
        //将内容写入管道中
        sc.write(writeBuffer);
        if (!writeBuffer.hasRemaining()) {
            //若缓冲区中无可读字节,则说明成功发送给服务器消息
            System.out.println("Send order 2 server succeed.");
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值