package NIONet;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.Scanner;
public class DatagramTest {
public static void main(String[] args) {
test1();
}
public static void test1() {
try {
DatagramChannel dc=DatagramChannel.open();
//设置成非阻塞模式
dc.configureBlocking(false);
ByteBuffer buf=ByteBuffer.allocate(1024);
Scanner scan=new Scanner(System.in);
while(scan.hasNext()) {
String content=scan.next();
buf.put(content.getBytes());
buf.flip();
dc.send(buf, new InetSocketAddress("127.0.0.1", 9898));
buf.clear();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
package NIONet;
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.Iterator;
public class ReceiveTtest {
public static void main(String[] args) {
receive();
}
public static 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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}