zoukankan      html  css  js  c++  java
  • 【Java nio】java nio笔记

    缓冲区操作:
    缓冲区,以及缓冲区如何工作,是所有I/O的基础。所谓“输入/输出”讲的无非就是把数据移出货移进缓冲区。
    进程执行I/O操作,归纳起来也就是向操作系统发出请求,让它要么把缓冲区里的数据排干,要么用数据把缓冲区填满。进程使用这一机制处理所有数据进出操作。
    Java.nio中的类被特意的设计为支持级联调用。
    Java NIO:
    Java NIO是一个可以替代标准Java IO API的IO API,Java NIO提供了与标准IO不同的IO工作方式。
    Java NIO:Channels and Buffers(通道和缓冲区)
    标准的IO基于字节流和字符流进行操作的,儿NIO是基于通道(Channel)和缓冲区(Buffer)进行操作,数据总是从通道读取到缓冲区中,或者从缓冲区写入到通道中。
    Java NIO:Non-blocking IO(非阻塞IO)
    Java NIO可以让你非阻塞的使用IO,例如:当线程从通道读取数据到缓冲区时,线程还是可以进行其他事情。当数据被写入到缓冲区时,线程可以继续处理它。从缓冲区写入到通道也类似。
    Java NIO:Selectors(选择器)
    Java NIO引入了选择器的概念,选择器用于箭筒多个通道的时间(比如:链接打开,数据到达)。因此,单个的线程可以坚挺多个数据通道。
    一、 Java NIO概述
    Java NIO由以下几个核心部分组成:
     Channels
     Buffers
     Selectors
    虽然Java NIO中除此之外还有很多类和组件,但是我看来,Channel ,Buffer ,Selector构成了核心的API。其他组件。如Pipe和FileLock,只不过是与三个核心组件共同使用的工具类。因此,在概述中我将其中在这三个组件上。其他组件会在单独的章节中讲到。
    Channels和Buffer
    基本上所有的IO在NIO中都从一个Channel开始。Channel有点象流。数据可以从Channel读取到Buffer中,也可以从Buffer写到Channel中

    Channel和Buffer有好几种类型。下面是JAVA NIO中的一些主要Channel的实现,这些通道涵盖了UDP和RCP网络IO,以及文件IO:
     FileChannel
     DatagramChannel
     SockekChannel
     ServerSocketChannel
    Java NIO中关键的Buffer的实现,这些Buffer覆盖了你能通过IO发送的基本类型数据:byte,short,int,long,float,double和char:
     ByteBuffer
     CharBuffer
     DoubleBuffer
     FloatBuffer
     IntBuffer
     LongBuffer
     ShortBuffer
    Java NIO 还有一个MappedByBuffer,用于表示内存映射文件,
    Selector:
    Selector允许单线程处理多个Channel,如果你的应用打开了多个连接(通道),但是每个连接的流量都很低,使用Selector就会很方便。
    例如在聊天服务器中,以下是一个单线程中使用Selector处理3个Channel的图示:

    要使用Selector,得向Selector注册Channel,然后调用他的select()方法。这个方法会一直阻塞到某个注册的通道有事件就绪。一旦这个方法返回,线程就可以处理这些事件,事件的例子有如新连接进来,数据接收等。
    二、 Channel
     Java NIO的通道类似流,但又有些不同:
     既可以从同道中读取数据,又可以写数据到通道。但流的读写同城是单向的。
     通道可以异步地读写。
     通道中的数据总是要读到一个Buffer,或者总是从一个Buffer中写入。

    Channel的实现:
     FileChannel:从文件中读写数据
     DatagramChannel:能通过UDP读写网络中的数据
     SocketChannel:能通过TCP读写网络中的数据
     ServerSocketChannel:可以监听新进来的TCP连接,像Web服务器那样。对每一个新进来的连接都会创建一个SocketChannel.
    基本Channel使用的示例:
    package com.slp.nio;

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

    /**
    * Created by sanglp on 2017/2/28.
    * Read48
    * package com.slp;

    * import java.util.concurrent.Read48
    * locks.Lock;

    * public class Main {

    * publicRead48
    * static void main(String[] args) {
    // write yoRead26
    * ur code here

    }
    }
    */
    public class FileChannelUse {
    public static void main(String []args){
    try {
    //为了以可读可写的方式打开文件使用RandomAccessFile来创建文件 以下两个相当于:FileChannel fc = new RandomAccessFile("D:\Project\InterviewPlan\src\com\slp\Main.java","rw").getChannel();
    RandomAccessFile accessFile = new RandomAccessFile("D:\Project\InterviewPlan\src\com\slp\Main.java","rw");
    FileChannel fileChannel = accessFile.getChannel();
    ByteBuffer buffer = ByteBuffer.allocate(48);
    int bytesRead = fileChannel.read(buffer);
    while (bytesRead!=-1){
    System.out.println("Read"+bytesRead);
    buffer.flip();//使用buffer.flip()首先读取数据到Buffer,然后又反转Buffer,接着从Buffer中读取数据
    while (buffer.hasRemaining()){
    System.out.print((char)buffer.get());
    }
    buffer.clear();
    bytesRead = fileChannel.read(buffer);
    }
    fileChannel.close();
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }


    三、 Buffer
    Java NIO中的Buffer用于和nio通道进行交互。数据是从通道读入缓冲区,从缓冲区写入到通道中的。
    缓冲区本质上是一块可以写入数据,然后可以从中读取数据的额内存,这块内存被包装成NIO Buffer对象,并提供了一组方法,用来方便的访问该块内存。
    1、 Buffer的基本用法
    使用Buffer读写数据一般遵循以下4个步骤:
     写入数据到Buffer
     调用flip()方法
     从Buffer中读取数据
     调用clear()方法或者compact()方法
    当向buffer写入数据时,buffer会记录下写了多少数据。一旦要读取数据,需要通过flip()方法将Buffer从写模式切入到度模式。在读模式下,可以读取之前写入到buffer的所有数据。
    一旦读完了所有的数据,需要清空缓冲区,让它可以再次被写入。有两种方式能清空缓冲区:调用clear()或者compact()方法,clear()会清空整个缓冲区,compact()方法只会清楚已经度过的数据。任何未读的数据都被移到缓冲区的起始处,新写入的数据将放到缓冲区未读取数据的后面。
    public class FileChannelUse {
    public static void main(String []args){
    try {
    //为了以可读可写的方式打开文件使用RandomAccessFile来创建文件 以下两个相当于:FileChannel fc = new RandomAccessFile("D:\Project\InterviewPlan\src\com\slp\Main.java","rw").getChannel();
    RandomAccessFile accessFile = new RandomAccessFile("D:\Project\InterviewPlan\src\com\slp\Main.java","rw");
    FileChannel fileChannel = accessFile.getChannel();
    ByteBuffer buffer = ByteBuffer.allocate(48);//create buffer with capacity of 48 bytes
    int bytesRead = fileChannel.read(buffer);
    //read into buffer
    while (bytesRead!=-1){
    System.out.println("Read"+bytesRead);
    // make buffer ready for read
    buffer.flip();//使用buffer.flip()首先读取数据到Buffer,然后又反转Buffer,接着从Buffer中读取数据
    while (buffer.hasRemaining()){
    System.out.print((char)buffer.get());//read 1 byte at a time
    }
    buffer.clear();//make buffer ready for writing
    bytesRead = fileChannel.read(buffer);
    }
    fileChannel.close();
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }


    2、 Buffer的capacity,position和limit
    缓冲区本质上是一块可以写入数据,然后可以从中读取数据的内存,这块内存被包装成NIO Buffer对象,并提供了一组方法,用来方便的访问该块内存。
    Buffer的单个属性:capacity position limit。 Position和limit的含义取决于Buffer处在读模式还是写模式。不管Buffer处在什么模式,capacity的含义总是一样的。

    Capacity:作为一个内存块,Buffer有一个固定的大小值,也叫capacity你只能往里写个byte long char 等类型,一旦Buffer满了,需要将其清空才能继续写数据往里写数据。
    Position:当写数据到Buffer中时,position表示当前的位置,初始的position值为0,当一个byte long等数据写到Buffer后,position会向钱移动到下一个科插入数据的Buffer单元。Position最大可为capacity-1
    当读取数据时,也是从某个特定位置读,当将Buffer从写模式切换到读模式,position会被重置为0,当从Buffer的position处读取数据时,position向前移动到下一个可读的位置。
    Limit:在写模式下,Buffer的limit表示你最多能往buffer里写多少数据,写模式下,limit等于Buffer的capacity.
    当切换Buffer到读模式时,limit表示最多能读到多少数据。因此,当切换Buffer到读模式时,limit会被设置成写模式下的position值。换句话说,你能读到之前写入的所有数据。

    3、 Buffer的类型
     ByteBuffer
     MappedByteBuffer
     CharBuffer
     DoubleBuffer
     FloatBuffer
     IntBuffer
     LongBuffer
     ShortBuffer
    4、 Buffer的分配
    要想获得一个Buffer对象首先要进行分配,每一个Buffer都有一个allocate方法。
    ByteBuffer buf = ByteBuffer.allocate(48);//ByteBuffer的例子
    CharBuffer buf = CharBuffer.allocate(1024);//CharBuffer的例子

    5、 向Buffer中写数据
    写数据到Buffer有两种方式:
     从Channel写到Buffer
    int bytesRead = inChannel.read(buf);

     通过Buffer的put()方法写到Buffer里
    buf.put(127);

    6、 Flip方法
    Flip方法将Buffer从写模式切换到读模式,调用flip()方法会将position设回0,并将limit设置成之前的position的值。
    换句话说,position现在用于标记读的位置,limit表示之前写进了多少个byte char
    7、 向Buffer中读取数据
     从Buffer读取数据到Channel
    int bytesWritten = inChannel.write(buf);

     使用get()方法从Buffer中读取数据
    byte abyte = buf.get();

    Buffer.rewind()将position设回0,所以你可以重读Buffer中的所有数据。Limit保持不变,仍然表示能从Buffer中读取多少个元素。
    8、 Clear()和compact()方法
    一旦Buffer中的数据读完,需要让Buffer准备好再次被写入。可以通过clear()或compact()方法来完成。Clear()方法position将被设置为0,limit被设置成capacity的值。Compact()方法将所有未读的数据拷贝到Buffer的起始处。
    9、 Mark()和reset()方法
    通过调用Buffer.mark()方法可以标记Buffer中的一个特定position,之后可以通过调用Buffer.reset()方法恢复到这个position
    10、 equals()和compareTo()方法
    满足如下条件时,说明两个Buffer相等:
     有相同的类型
     Buffer中剩余的byte char等的个数相等
     Buffer中所有剩余的byte char等都相同
    CompareTo()方法比较两个Buffer的剩余元素如果满足如下则认为一个Buffer小于另一个Buffer:
     第一个不相等的元素小于另一个Buffer中对应的元素
     所有元素都相等,但是一个Buffer比另一个先耗尽
    四、 Scatter/Gather
    Java NIO开始支持scatter/gather,scatter/gather用于描述从Channel中读取或者写入到Channel的操作。
    分散(scatter)从Channel中读取是指在读操作时将读取的数据写入多个buffer中。因此Channel将从channel中读取到的数据分散到多个Buffer 中。
    聚集(gather)写入Channel是指在写操作时将多个Buffer的数据写入同一个Channel中因此,Channel将多个Buffer中的数据聚集后发送到Channel。
    Scatter/gather经常用于需要将传输的数据分开处理的场合,例如传输一个由消息透和消息体组成的消息,你可能会将消息体和消息透分散到不同的buffer中,这样你可以方便的的处理消息头和消息体。
    Scattering Reads :是指数据从一个channel读取到多个buffer中
    ByteBuffer header= ByteBuffer.allocate(128);
    ByteBuffer body = ByteBuffer.allocate(1024);
    ByteBuffer[] bufferArray = {header,body};
    Channel.read(bufferArray)
    注意buffer首先被插入到数组,然后再将数组作为channel.read()的输入参数。Read()方法按照buffer在数组中的顺序将从channel中读取到的数据写入到buffer,当一个buffer被写满后,channel紧接着向另一个buffer写。
    Scattering Reads在移动下一个buffer前,必须填满当前的buffer,这也意味着他不适合用于动态消息。换句话说,如果存在消息头和消息体,消息头必须完成填充,Scattering Reads才能正常工作。
    Gathering Writes:是指数据从多个Buffer写入到同一个channel
    ByteBuffer header = ByteBuffer.allocate(128);
    ByteBuffer body = ByteBuffer.allocate(1024);
    ByteBuffer[] bufferArray ={header,body};
    Channel.write(bufferArray);
    Buffers数组是write()方法的入参,write()方法会按照buffer在数组中的顺序,将数据写入到channel,注意只有position和limit之间的数据才会被写入。因此,如果一个buffer的容量为128byte,但是仅仅包含58bytes的数据,那么这58byte的数据将被写入到channel中,因此与Scattering Reads相反,Gathering Writes能较好的处理动态消息。
    五、 通道之间的数据传输
    在Java NIO中,如果两个通道中有一个是FileChannel,那你可以直接将数据从一个channel传输到另一个channel
    TransferFrom():FileChannel的transferFrom()方法可以将数据从源通道传输到FileChannel中。
    RandomAccessFile fromFile = new RandomAccessFie(“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)
    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();
    fromChannel.transferTo(position,count,toChannel);
    六、 Selector
    Selector(选择器)是Java nio中能够检测一到多个NIO通道,并能够知晓通道是否为诸如读写事件做好准备的组件。这样,一个单独的线程可以管理多个chnnel,从而管理多个网络连接。
    1、 为什么使用selector
    仅用单个线程来处理多个Channels的好处是,值需要更少的线程来处理通道。事实上,可以只用一个线程处理所有的通道,对于操作系统来说,线程之间上下文切换的开销很大,而且每个线程都要占用系统的一些资源。因此,使用的线程越少越好。
    2、 Selector的创建
    Selector selector = Selector.open();

    3、 向selector注册通道
    Channel.configureBlocking(false);
    SelectionKey key = channel.register(selector,Selectionkey.OP_READ);
    与selector一起使用时channel必须处于非阻塞模式。这意味着不能将FileChannel与Selector一起使用,因为FileChannel不能切换到非阻塞模式。而套接字通道都可以。

    4、 SelectionKey
    当向Selector注册Channel时,register()方法会返回一个SelectionKey对象。这个对象包含了
     Interest集合:
    Interest集合是你所选择的感兴趣的事件集合
    Int interestSet = selectionKey.interestOps();
    Boolean isInterestedInAccept = (interestSet & SelectionKey.OP_ACCEPT)==SelectionKey.OP_ACCEPT;
    boolean isInterestedInRead = interestSet & SelectionKey.OP_READ;
    boolean isInterestedInConnect = interestSet & SelectionKey.OP_CONNECT;
    boolean isInterestedInWrite = interestSet & SelectionKey.OP_WRITE;

     Ready集合
    通道已经准备就绪的操作的集合。在一次选择之后,你会首先访问这个ready set
    Int readySet = selectionKey.readyOps();
    可以像检测interest集合那样的方法,来检测channel中什么事件或操作已经就绪
    SelectionKey.isAcceptable()
    SelectionKey.isConnectable();
    SelectionKey.isReadable();
    SelectionKey.isWritable();

     Channel
     Selector
    从selectionkey访问Channel和Selector的方法
    Channel channel = selectionKey.channel();
    Selector selector = selectionKey.selector();

    5、 通过Selector选择通道
    一旦向Selector注册了一个或多个通道,就可以调用接重载的select()方法,这些方法返回你所感兴趣的事件(连接 接受 读或写)已经准备就绪的那些通道,换句话说,如果你对读继续的通道感兴趣,select()方法会返回读事件已经就绪的那些通道
     Int select():阻塞到至少有一个通道在你注册的事件上就绪了
     Int select(long timeout):除了最长会阻塞timeout毫秒
     Int selectNow():不会阻塞,不管什么通道阻塞都立刻返回
    Select()方法返回的int值表示有多少通道已经就绪,也就是自上次调用select()方法后有多少通道变成就绪状态,如果调用select()方法,因为有一个通道变成就绪状态返回了1,若再次调用select()方法,如果返回另一个通道就绪了,他会再次返回1如果对第一个就绪的channel没有做任何操作,现在就有两个就绪的通道,但咋每次select()方法调用之间,只有一个通道就够了。
    6、 Wakeup():某个线程调用select()方法后阻塞了,即使没有通道已经就绪,也有办法让其从select()方法返回。只要让其他线程在第一个线程调用select()方法的那个对象上调用wakeup()方法就可以
    7、 Close();用完selector后调用close()方法会关闭该Selector,且使注册到该selector上的所有selectionKey实例无效。通道本身并不会关闭。
    8、 完整的示例
    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.selectdKeys();
    Iterator keyIterator =selectedKeys.iterator();
    While(keyIterator.hasNext()){
    SelectionKey key = keyIterator.next();
    If(key.isAcceptable()){


    }else if(key.isConnectable()){

    }else if(key.isReadable()){
    }else if(key.isWritable()){
    }
    KeyIterator.remove();
    }}
    七、 FileChannel
    Java nio的FileChannel是一个连接到文件的通道。可以通过文件通道的读写操作。
    FileChannel无法设置为非阻塞模式他总是允许在阻塞模式下。
    打开FileChannel:在使用FileChannel之前,必须先打开它。但是,我们无法直接打开一个FileChannel,需要通过使用一个InputStream OutputStream RandomAccessFile来获取一个FileChannel实例。
    RandomAccessFile afile = new RandomAccessFile(“”,”rw”);
    FileChannel inchannel = afile.getChannel();

    从FileChannel读取数据:
    调用多个read()方法之一从FileChannel读取数据:
    ByteBuffer buf = ByteBuffer.allocate(48);
    Int byteRead = inChannel.read(buf);
    首先,分配一个Buffer,从FileChannel中读取的数据将被读到Buffer中。
    然后,调用FileChannel.read()方法,该方法将数据从FileChannel读取到Buffer中,read()方法返回的int值表示有多少个字节被读取到了buffer中。如果是-1表示到了文件末尾。
    向FileChannel写数据:
    使用FileChannel.write()方法向FileChannel写数据,该方法的参数是一个Buffer
    String newData = “ACCCCCCCC”;
    System.currentTimeMillis();
    ByteBuffer buf = ByteBuffer.allocate(48);
    Buf.clear();
    Buf.put(newData.getbytes());
    Buf.flip();
    While(buf.hasRemaining()){
    Channel.write(buf);
    }
    关闭FileChannel:channel.close();
    FileChannel的position方法
    有时可能需要在FileChannel的某个特定位置进行数据的读/写操作。可以通过调用position()方法获取FileChannel的当前位置。
    也可以通过调用position(long pos)方法设置FileChannel的当前位置。
    这里有两个例子:
    1 long pos = channel.position();
    2 channel.position(pos +123);
    如果将位置设置在文件结束符之后,然后试图从文件通道中读取数据,读方法将返回-1 —— 文件结束标志。
    如果将位置设置在文件结束符之后,然后向通道中写数据,文件将撑大到当前位置并写入数据。这可能导致“文件空洞”,磁盘上物理文件中写入的数据间有空隙。
    FileChannel的size方法
    FileChannel实例的size()方法将返回该实例所关联文件的大小。如:
    1 long fileSize = channel.size();
    FileChannel的truncate方法
    可以使用FileChannel.truncate()方法截取一个文件。截取文件时,文件将中指定长度后面的部分将被删除。如:
    1 channel.truncate(1024);
    这个例子截取文件的前1024个字节。
    FileChannel的force方法
    FileChannel.force()方法将通道里尚未写入磁盘的数据强制写到磁盘上。出于性能方面的考虑,操作系统会将数据缓存在内存中,所以无法保证写入到FileChannel里的数据一定会即时写到磁盘上。要保证这一点,需要调用force()方法。
    force()方法有一个boolean类型的参数,指明是否同时将文件元数据(权限信息等)写到磁盘上。
    八、 SocketChannel
    Java NIO中的SocketChannel是一个连接到TCP网络套接字的通道。可以通过如下两个方式进行创建:
     打开一个SocketChannel并连接到互联网上的某台服务器
     一个新连接到达ServerSocketChannel时,会创建一个SocketChannel
    打开SocketChannel:
    SocketChannel socketChannel = SocketChannel.open();
    socketChannel.connect(new InetSocketAddress("http://baisu.com",80));
    关闭SocketChannel:
    socketChannel.close();
    从SocketChannel读取数据:
    //从SocketChannel读取数据
    ByteBuffer buffer = ByteBuffer.allocate(48);//首先分配一个Buffer,从SocketChannel读取到的数据将会放到Buffer中
    int bytesRead =socketChannel.read(buffer);//调用read()方法,该方法将数据从SocketChannel读到Buffer中。返回的int表示读取了多少字节到Buffer里
    写入SocketChannel:
    //写入到SocketChannel
    String newData = "ASDFFF";
    System.currentTimeMillis();
    ByteBuffer buffer1 = ByteBuffer.allocate(48);
    buffer1.clear();
    buffer1.put(newData.getBytes());
    buffer1.flip();
    while (buffer1.hasRemaining()){
    socketChannel.write(buffer1);
    }
    非阻塞模式:
    可以设置SocketChannel为非阻塞模式,设置之后,就可以异步模式下调用connect(),read() write()了。
     connect():
    如果SocketChannel在非阻塞模式下,此时调用connect(),该方法可能在连接建立之前就返回了。为了确定是否连接,可以调用finishConnect()的方法。
    SocketChannel socketChannel = SocketChannel.open();
    socketChannel.configureBlocking(false);
    socketChannel.connect(new InetSocketAddress("http://baisu.com",80));
    while (!socketChannel.finishConnect()){
    }
     write()
    非阻塞模式下,write()方法尚未写出任何内容时可能就返回了,所以需要重复调用。
     read()
    非阻塞模式下,read()方法尚未读取到任何数据时可能就返回了,所以需要关注他的返回int的值。
    非阻塞模式与选择器:
    非阻塞模式与选择器搭配会工作的更好,通过将一或多个SocketChannel注册到Selector,可以询问选择器哪个通道已经准备好了读取。写入等。
    九、 ServerSocketChannel
    Java NIO中的ServerSocketChannel是一个可以坚挺新进来的TCP连接的通道,就像标准IO中的ServerSocket一样。ServerSocketChannel类在java.nio.chennels包中
    //打开ServerSocketChannel
    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.socket().bind(new InetSocketAddress(9999));
    while (true){
    //监听新进来的连接,当accept()返回的时候他返回一个包含新进来的连接的SocketChannel.所以accept()会一直阻塞到有新连接到达。
    SocketChannel socketChannel = serverSocketChannel.accept();

    }

    非阻塞模式:
    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){

    }
    }
    十、 DatagramChannel
    DatagramChannel十一个接收UDP包的通道,因为UDP是无连接的网络协议,所以不能像其他通道那样读取和写入,他发送和接收的都是数据包。
    //打开DatagramChannel, 可以在UDP端口9999上接收数据包
    DatagramChannel datagramChannel = DatagramChannel.open();
    datagramChannel.socket().bind(new InetSocketAddress(9999));
    //接收数据 receive()方法将会接收到的数据包内容复制到指定的Buffer,如果Buffer容不下收到的数据,多出的数据将被丢弃。
    ByteBuffer buffer = ByteBuffer.allocate(48);
    buffer.clear();
    datagramChannel.receive(buffer);
    //发送数据
    String newData = "ASDFGGG";
    System.currentTimeMillis();
    ByteBuffer buffer1 = ByteBuffer.allocate(48);
    buffer1.clear();
    buffer1.put(newData.getBytes());
    buffer1.flip();
    int bytesSent = datagramChannel.send(buffer1,new InetSocketAddress("baidu.com",80));
    十一、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 buffer = ByteBuffer.allocate(48);
    int bytesRead = sourceChannel.read(buffer);//read()方法返回的int告诉我们多少字节读进了缓冲区

  • 相关阅读:
    tomcat配置通过域名直接访问项目首页步骤
    kafka配置参数
    nginx平滑升级
    redsi一主两从三哨兵
    kill
    lelnet爱一直在
    在linux中查看进程占用的端口号
    监控redis
    老猿学5G随笔:RAN、RAT以及anchor移动性锚点的概念
    老猿学5G随笔:5G网元功能体NF以及NF之间的两种接口--服务化接口和参考点
  • 原文地址:https://www.cnblogs.com/dream-to-pku/p/6484049.html
Copyright © 2011-2022 走看看