java-NIO

来源:互联网 发布:芜湖cnc编程招聘 编辑:程序博客网 时间:2024/05/18 01:28

java NIO

[原文链接](http://http://ifeve.com/socket-channel/) 作者:Jakob Jenkov 译者:郑玉婷 校对:丁一

1.核心部分

Channels: 数据可以从Channel读到Buffers中,也可以从Buffets中写        到Channel    主要实现:FileChannel  DatagramChannel SocketChannelBuffers:      主要实现:ByteBuffer,CharBuffer,DoubleBuffer等基本数据类型。(MapperdByteBuffter:特殊)Selectors:  允许多个单线程处理多个Channel。

2.Channels

1.可以从通道中读写数据,与流的区别在于流的读写基本是单向的2.通道可以异步读写3.通道中的数据先要读到一个buffer,或者总是要从一个Buffer中写入
主要的实现
1)fileChannel:从文件中读写数据2)DatagramChannel:通过udp读写网络的数据3)SocketChannel能通过TCP读写网络中的数据4)serverSocketChannel:可以箭筒新进来的TCP链接,对于每一个新进来的链接都会创建一个一个SocketChannel
例子:
RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw");    FileChannel inChannel = aFile.getChannel();    ByteBuffer buf = ByteBuffer.allocate(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();ps:先读到数据到Buffer,然后翻转它,再从Buffer中读取数据

3.Buffers

用于NIO的通道进行交互,数据是从通道中读入缓冲区,从缓冲区中写入通道。
基本用法
一般为四个步骤:1)写入数据到Buffer2)调用flip()方法3)从buffer中读取数据4)调用Clear()方法或者compact()方法当向Buffer写入数据时,buffer会记录写了多少数据,一旦读取数据,需要通过flip()方法将Buffers从写模式转换到读模式。在读模式下,可以读取之前写入到bffer的所有数据。一旦读完了所有的数据,就需要清空缓冲区,让它可以再次被写入,清空缓冲区的两种方法区别在于:clear()会清空整个缓冲区,compact()只会清除已经度过的数据。任何未读的数据都会移动缓冲区的起始处。新写入的数据将放到缓冲区未读数据的后面。具体例子:RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw");    FileChannel inChannel = aFile.getChannel();    //create buffer with capacity of 48 bytes    ByteBuffer buf = ByteBuffer.allocate(48);    int bytesRead = inChannel.read(buf); //read into buffer.    while (bytesRead != -1) {      buf.flip();  //make buffer ready for read      while(buf.hasRemaining()){          System.out.print((char) buf.get()); // read 1 byte at a time      }      buf.clear(); //make buffer ready for writing      bytesRead = inChannel.read(buf);    }    aFile.close();
Buffer的capacity,position和limit
缓冲区本质上是一块可以写入数据,然后可以从中读取数据的内存。这块内存被包装秤NIO buffer对象,并提供了一组方法,用来方便的访问该块内存。Buffer的三个属性:1)capacity:作为一个内存块,Buffer有一个固定的大小值没也叫capacity,而且只能往里写capacity个byte,long,char等类型,一旦满了,需要将其清空才能继续写数据。2)position:当你写数据到buffer时position表示当前的位置,初始的position的值为0,当一个byte,long等数据写到其中时,position就会先前移动到下一个可以插入的单元。position最大可为capacity-1;当读取数据时,也是从某个特定位置读,当将buffer从写模式切换到读模式时,position就会重置为0,同理,当切换成写模式时,就为移动到下一个可写位置单元。3)limit在写模式下,buffer的limit表示你最能往buffer里写多少数据,写模式下,limit等于buffer的capacity,当切换buffer到读模式时,limit表示你最多呢个读到多少数据,因此,当切换到读模式时,limit就换呗设置为写模式下的position值,换句话说,你能读到之前写入的所有数据。
Buffer的类型
Java NIO 有以下Buffer类型    ByteBuffer    MappedByteBuffer    CharBuffer    DoubleBuffer    FloatBuffer    IntBuffer    LongBuffer    ShortBuffer
Buffer的分配
要想获得一耳光buffer对象首先要进行分配,每一个buffer类都有一个allocate方法,如下例子。ByteBuffer buf=ByteBuffer.allocate(48);//分配48个字节的capacity
flip()方法
将写模式切换成读模式。
从Buffer中读取数据
从Buffer中读取数据的两种方式:1.buffer读取数据到Channel    int bytesWritten =inChannel.write(buf);//从buffer中读取数据到通道2.使用get()从buffer中读取数据    byte abyte =buf.get();
rewind()方法
Buffer.rewind()将position设回0,所以你可以重新读取Buffer中的所有数据,limit保持不变,仍然表示能从Buffer中读取多少个元素。
clear()与compact()方法
一旦读完Buffer中的数据,需要让Buffer准备好再次被写入。可以通过clear()或compact()方法来完成。如果调用的是clear()方法,position将被设回0,limit被设置成 capacity的值。换句话说,Buffer 被清空了。Buffer中的数据并未清除,只是这些标记告诉我们可以从哪里开始往Buffer里写数据。如果Buffer中有一些未读的数据,调用clear()方法,数据将“被遗忘”,意味着不再有任何标记会告诉你哪些数据被读过,哪些还没有。如果Buffer中仍有未读的数据,且后续还需要这些数据,但是此时想要先先写些数据,那么使用compact()方法。compact()方法将所有未读的数据拷贝到Buffer起始处。然后将position设到最后一个未读元素正后面。limit属性依然像clear()方法一样,设置成capacity。现在Buffer准备好写数据了,但是不会覆盖未读的数据。
mark()与reset()方法
通过调用Buffer.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.
quals()与compareTo()方法
1)equals()当满足下列条件时,表示两个Buffer相等:    有相同的类型(byte、char、int等)。    Buffer中剩余的byte、char等的个数相等。    Buffer中所有剩余的byte、char等都相同。如你所见,equals只是比较Buffer的一部分,不是每一个在它里面的元素都比较。实际上,它只比较Buffer中的剩余元素。2)compareTo()方法compareTo()方法比较两个Buffer的剩余元素(byte、char等), 如果满足下列条件,则认为一个Buffer“小于”另一个Buffer:    第一个不相等的元素小于另一个Buffer中对应的元素 。    所有元素都相等,但第一个Buffer比另一个先耗尽(第一个Buffer的元素个数比另一个少)。

4.Scatter/Gather

1)scatter(分散):从Channel中读取是指在读操作时将读取的数据写入多个buffer中,因此Channel将从Channel中读取的数据分散到多个buffer中。2)gather(聚集):写入Channel是指在写操作时将多个buffer的数据写入同一个Channel,因此,Channel将多个Buffer的数据聚集后发送到channel,通常,一般用于需要将传输的数据分开处理的场合,如传输一个消息头和消息体组成的消息,可能会将消息体与消息头分散到不同的buffer中,这样你可以方便的处理消息头和消息体。

Scattering reads

Scattering reads 是指数据从一个Channerl读取到多个buffer中。实例:Bytebuffer header =bytebuffer.allocate(128);ByteBuffer body= ByteBuffer.allocate(1024); Bytebuffer[]  bufferArray={header,body};channel.read(bufferArray);Scattering Reads在移动下一个buffer前,必须填满当前的buffer,这也意味着它不适用于动态消息(译者注:消息大小不固定)。换句话说,如果存在消息头和消息体,消息头必须完成填充(例如 128byte),Scattering Reads才能正常工作。

Gathering Writes

实例:ByteBuffer header= ByteBuffer.allocate(128);ByteBuffer body=ByteBuffer.allocate(1024);ByteBuffer[]  bufferArray={header,body};channel.write(bufferArray);

5.通道之间的数据传输

如果两个通道中,有一个是fileChannel ,那你可以直接将数据从一个Channel传输懂啊另外一个channel.
transferFrom():FileChannel的transferFrom()方法可以将数据从源通道传输到FileChannel中(译者注:这个方法在JDK文档中的解释为将字节从给定的可读取字节通道传输到此通道的文件中)。下面是一个简单的例子:    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(fromChannel,position, count);方法的输入参数position表示从position处开始向目标文件写入数据,count表示最多传输的字节数。如果源通道的剩余空间小于 count 个字节,则所传输的字节数要小于请求的字节数。此外要注意,在SoketChannel的实现中,SocketChannel只会传输此刻准备好的数据(可能不足count字节)。因此,SocketChannel可能不会将请求的所有数据(count个字节)全部传输到FileChannel中。
transferTo()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);是不是发现这个例子和前面那个例子特别相似?除了调用方法的FileChannel对象不一样外,其他的都一样。上面所说的关于SocketChannel的问题在transferTo()方法中同样存在。SocketChannel会一直传输数据直到目标buffer被填满。 

6.Selector

Sekector 是java NIO中能够检测一到多个NIO通道,并能能够知晓通道是否为诸多读写事件做好准备的组件。可以帮助一个线程管理多个channel,从而管理多个网络连接。

使用selector的原因

仅用单线程处理多个channels的好处是,只需要更少的线程来处理童丹,事实上,可以只用一个线程来处理所有通道,对于操作系统而言,线程之间的上下文切换开销很大,而且每个线程占用系统的一些资源,因此线程越少越好。但是,需要记住,现代的操作系统和CPU在多任务方面表现的越来越好,所以多线程的开销随着时间的推移,变得越来越小了。实际上,如果一个CPU有多个内核,不使用多任务可能是在浪费CPU能力。不管怎么说,关于那种设计的讨论应该放在另一篇不同的文章中。在这里,只要知道使用Selector能够处理多个通道就足够了。

selector处理三个channel的示例

//创建一个selectorSelector selector=Selector.open();//向selector注册通道channel.configureBlocking(false);//非阻塞模式下SelectionKey key= channel.ragister(selector,SelectionKey.OP_READ);ps:因为channel必须处于阻塞模式下,这意味着不能将FileChannel与Selector一起使用,因为FileChannel不能切换到非阻塞模式。而套接字通道都可以。注意register()方法的第二个参数。这是一个“interest集合”,意思是在通过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;

SelectionKey

当向Selector注册Channel时,register()方法会返回一个SelectionKey对象。这个对象包含了一些你感兴趣的属性:    interest集合    ready集合    Channel    Selector    附加的对象(可选)下面我会描述这些属性。interest集合就像向Selector注册通道一节中所描述的,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;可以看到,用“位与”操作interest 集合和给定的SelectionKey常量,可以确定某个确定的事件是否在interest 集合中。ready集合ready 集合是通道已经准备就绪的操作的集合。在一次选择(Selection)之后,你会首先访问这个ready set。Selection将在下一小节进行解释。可以这样访问ready集合:    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();附加的对象可以将一个对象或者更多信息附着到SelectionKey上,这样就能方便的识别某个给定的通道。例如,可以附加 与通道一起使用的Buffer,或是包含聚集数据的某个对象。使用方法如下:    selectionKey.attach(theObject);    Object attachedObj = selectionKey.attachment();还可以在用register()方法向Selector注册Channel的时候附加对象。如:    SelectionKey key = channel.register(selector, SelectionKey.OP_READ, theObject);通过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()方法调用之间,只有一个通道就绪了。selectedKeys()一旦调用了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();    }这个循环遍历已选择键集中的每个键,并检测各个键所对应的通道的就绪事件。注意每次迭代末尾的keyIterator.remove()调用。Selector不会自己从已选择键集中移除SelectionKey实例。必须在处理完通道时自己移除。下次该通道变成就绪时,Selector会再次将其放入已选择键集中。SelectionKey.channel()方法返回的通道需要转型成你要处理的类型,如ServerSocketChannel或SocketChannel等。wakeUp()某个线程调用select()方法后阻塞了,即使没有通道已经就绪,也有办法让其从select()方法返回。只要让其它线程在第一个线程调用select()方法的那个对象上调用Selector.wakeup()方法即可。阻塞在select()方法上的线程会立马返回。如果有其它线程调用了wakeup()方法,但当前没有线程阻塞在select()方法上,下个调用select()方法的线程会立即“醒来(wake up)”。close()用完Selector后调用其close()方法会关闭该Selector,且使注册到该Selector上的所有SelectionKey实例无效。通道本身并不会关闭。完整的示例这里有一个完整的示例,打开一个Selector,注册一个通道注册到这个Selector上(通道的初始化过程略去),然后持续监控这个Selector的四种事件(接受,连接,读,写)是否就绪。查看源代码    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

fileChannel 代表一个连接文件的通道,可以通过文件通道来读写文件。注意:filechannel无法设置非阻塞模式,它总是运行在阻塞模式下。
1)打开fileChannel   //一般而言,我们无法直接打开一个fileChannel  需要通过一个inputstream,outputstream或randomaccessFile来获取一个filechannel实例。如:    RandomAccessFile aFile =new RandomAccessFile("data/nio-date-txt","rw");    FileChannel inChannel=aFile.getChannel();2)读取数据    ByteBuffer buf=ByteBuffeer,allocate(48);    int byteRead=inChannel.read(buf);    如果返回byteRead=-1 表示读到了文件的末尾。3)写数据    String data="hello";    ByteBuffer buf=ByteBuffer.allocate(48);    buf.clear();    buf.put(data.getBytes());    buf.flip();    while(buf.hasRemaining())    {        channel.wirte(buf);    }注意FileChannel.write()是在while循环中调用的。因为无法保证write()方法一次能向FileChannel写入多少字节,因此需要重复调用write()方法,直到Buffer中已经没有尚未写入通道的字节。4)关闭通道,channel.close();5)如果需要在FileChannel的某个特定位置进行数据的读写操作,可以通过调用position()方法获取FileChannel的当前位置,或者通过position(long pos)方法设置当前位置:如: long pos=channel.position(); channel.position(pos+123);6)size()方法 可以发回当前实例关联的文件大小。    long filesize=channel.size();7)truncate方法  可以使用FileChannel.truncate()方法来截取一个文件,截取文件时,文件将中指定长度后面的部分将其删除,如    channel。truncate(1024);8)force方法 将通道里尚未写入磁盘的数据强制写到磁盘中。 如:channel.force(true);

8.SocketChannel

SocketChannel 是一个可以连接到tcp网络套接字的通道。两种创建方式:、1)打开一个SocketChannel并连接到互联网上的某台服务器。2)一个新连接到达serverSocketChannel中时,会创建一个SocketChannel

打开SocketChannel

   SocketChannel socketChannel =SocketChannel.open();   socketChannel.connect(new InetSocketAdress("http://jenkov.com",80));

关闭SocketChannel

socketChannel.close;

读取数据

 ByteBuffer buf=ByteBuffer.allocate(48); int byteRead=socketBuffer.read(buf);

写入数据

String data="hello";ByteBuffer buf=ByteBuffer.allocate(48);buf.clear();buf.put(data.getByets());buf.flip();while(buf.hasRemaining()){    channel.werite(buf);}注意SocketChannel.write()方法的调用是在一个while循环中的。Write()方法无法保证能写多少字节到SocketChannel。所以,我们重复调用write()直到Buffer没有要写的字节为止。

非阻塞模式

可以设置SocketChannel为非阻塞模式,设置之后,可以在异步模式下调用connect(),read()和write()1)connect()如果SocketChannel在非阻塞模式下,此时调用connect ,该方法可能在连接建立之前就返回了,为了确保连接是否建立,可以调用finishConnect()方法。socketChannel.configureBlocking(false);socketChannel.connect(new InteSocketAddress("htto://baidu.com",80));while(!socketChannel.finishConnect()){//wait, or do something else...}write()非阻塞模式下,write()方法在尚未写出任何内容时可能就返回了。所以需要在循环中调用write()。前面已经有例子了,这里就不赘述了。read()非阻塞模式下,read()方法在尚未读取到任何数据时可能就返回了。所以需要关注它的int返回值,它会告诉你读取了多少字节。非阻塞模式与选择器非阻塞模式与选择器搭配会工作的更好,通过将一或多个SocketChannel注册到Selector,可以询问选择器哪个通道已经准备好了读取,写入等。Selector与SocketChannel的搭配使用会在后面详讲

9.ServerSocketChannel

Java NIO中的 ServerSocketChannel 是一个可以监听新进来的TCP连接的通道, 就像标准IO中的ServerSocket一样。ServerSocketChannel类在 java.nio.channels包中。ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();    serverSocketChannel.socket().bind(new InetSocketAddress(9999));    while(true){        SocketChannel socketChannel =                serverSocketChannel.accept();        //do something with socketChannel...    }
打开 ServerSocketChannel通过调用 ServerSocketChannel.open() 方法来打开ServerSocketChannel.如:1    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();关闭 ServerSocketChannel通过调用ServerSocketChannel.close() 方法来关闭ServerSocketChannel. 如:1    serverSocketChannel.close();监听新进来的连接通过 ServerSocketChannel.accept() 方法监听新进来的连接。当 accept()方法返回的时候,它返回一个包含新进来的连接的 SocketChannel。因此, accept()方法会一直阻塞到有新连接到达。通常不会仅仅只监听一个连接,在while循环中调用 accept()方法. 如下面的例子:1    while(true){2        SocketChannel socketChannel =3                serverSocketChannel.accept();45        //do something with socketChannel...6    }当然,也可以在while循环中使用除了true以外的其它退出准则。非阻塞模式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.Java NIO DatagramChannel

Java NIO中的DatagramChannel是一个能收发UDP包的通道。因为UDP是无连接的网络协议,所以不能像其它通道那样读取和写入。它发送和接收的是数据包。
打开 DatagramChannel下面是 DatagramChannel 的打开方式:    DatagramChannel channel = DatagramChannel.open();    channel.socket().bind(new InetSocketAddress(9999));这个例子打开的 DatagramChannel可以在UDP端口9999上接收数据包。接收数据通过receive()方法从DatagramChannel接收数据,如:    ByteBuffer buf = ByteBuffer.allocate(48);    buf.clear();    channel.receive(buf);receive()方法会将接收到的数据包内容复制到指定的Buffer. 如果Buffer容不下收到的数据,多出的数据将被丢弃。发送数据通过send()方法从DatagramChannel发送数据,如:    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));这个例子发送一串字符到”jenkov.com”服务器的UDP端口80。 因为服务端并没有监控这个端口,所以什么也不会发生。也不会通知你发出的数据包是否已收到,因为UDP在数据传送方面没有任何保证。连接到特定的地址可以将DatagramChannel“连接”到网络中的特定地址的。由于UDP是无连接的,连接到特定地址并不会像TCP通道那样创建一个真正的连接。而是锁住DatagramChannel ,让其只能从特定地址收发数据。这里有个例子:    channel.connect(new InetSocketAddress("jenkov.com", 80));当连接后,也可以使用read()和write()方法,就像在用传统的通道一样。只是在数据传送方面没有任何保证。这里有几个例子:查看源代码    int bytesRead = channel.read(buf);    int bytesWritten = channel.write(but);

11.Pipe

java nio 管道式两个线程之间的单向数据连接,pipe有一个source通道和sink通道,数据会被写到sink通道中,从source通道中读取。

调用

//创建管道Pipe pipe=Pipe.open();//写数据Pipe.SinkChannel sinkChannel =pipe.sink();String data="hello";ByteBuffer buf=ByteBuffer.allocate(48);buf.clear();buf.put(data.getBytes());buf.flip();while(buf.hasRemaining()){    sinkChannel.write(buf);}//读数据Pipe.SourceChannel sourceChannel =pipe.source();ByteBuffer buf=ByteBuffer.allocate(48);int byteRead=sourceChannel.read(buf);
0 0