NIO学习(一)----Buffer
NIO学习(二)----Channel
NIO学习(三)----Selector
NIO学习(四)----DatagramChannel和管道(pipe)
DatagramChannel
1.Java NIO中的DatagramChannel是一个能接收发UDP包的通道
2.操作步骤
1).打开DatagramChannel
2).接收/发送数据
package com.wxl.nio;
import org.junit.Test;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Date;
import java.util.Iterator;
import java.util.Scanner;
public class TestNonBlockingNIO2 {
@Test
public void send(){
try {
DatagramChannel dc = DatagramChannel.open();
dc.configureBlocking(false);
ByteBuffer buf = ByteBuffer.allocate(1024);
Scanner scan = new Scanner(System.in);
while (scan.hasNext()){
String str = scan.next();
buf.flip();
buf.put((new Date().toString()+"+\n"+str).getBytes());
dc.send(buf,new InetSocketAddress("127.0.0.1",9898));
buf.clear();
}
dc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void receive(){
try {
DatagramChannel dc = DatagramChannel.open();
dc.configureBlocking(false);
dc.bind(new InetSocketAddress(9898));
Selector selector = Selector.open();
dc.register(selector, SelectionKey.OP_READ);
while (selector.select()>0){
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()){
SelectionKey sk = it.next();
if (sk.isReadable()){
ByteBuffer buf = ByteBuffer.allocate(1024);
dc.receive(buf);
buf.flip();
System.out.println(new String(buf.array(),0,buf.limit()));
buf.clear();
}
}
it.remove();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
管道(pipe)
Java NIO 管道是两个线程之间的单向数据连接。Pipe有一个source通道和一个sink通道。数据会被写到sink通道,从source通道读取。
package com.wxl.nio;
import org.junit.Test;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
public class TestPipe {
@Test
public void Test1(){
try {
//1.获取管道
Pipe pipe = Pipe.open();
//2.将缓冲区的数据写入管道
ByteBuffer buf = ByteBuffer.allocate(1024);
Pipe.SinkChannel sinkChannel = pipe.sink();
buf.put("通过管道发送数据".getBytes());
buf.flip();
sinkChannel.write(buf);
//3.读取缓冲区中的数据
Pipe.SourceChannel sourceChannel = pipe.source();
buf.flip();
int len = sourceChannel.read(buf);
System.out.println(new String(buf.array(),0,len));
sourceChannel.close();
sinkChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}