import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
public class Demo07 {
//客户端
public static void main(String[] args) throws IOException {
DatagramChannel dc = DatagramChannel.open();
dc.configureBlocking(false);
ByteBuffer buffer = ByteBuffer.allocate(1024);
String msg = "hello udp";
buffer.put(msg.getBytes());
buffer.flip();
dc.send(buffer, new InetSocketAddress("127.0.0.1", 9009));
}
}
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;
import java.util.Set;
public class Demo06 {
//服服务端
public static void main(String[] args) throws Exception {
int port = 9009;
Selector selector = Selector.open();
//和TCP的对象不一样
DatagramChannel dc = DatagramChannel.open();
dc.configureBlocking(false);
dc.bind(new InetSocketAddress(port));
dc.register(selector, SelectionKey.OP_READ);
while (true) {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> it = keys.iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
if (key.isReadable()) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
dc.receive(buffer);
buffer.flip();
System.out.println(new String(buffer.array(), 0, buffer.limit()));
}
it.remove();
}
}
}
}
Pipe通道
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
public class Demo08 {
public static void main(String[] args) throws Exception {
//打开通道
Pipe pipe = Pipe.open();
// sink 数据写到这里面
// sourse 通过他读出来
Thread s = new Thread(new Sender(pipe));
Thread r = new Thread(new Recv(pipe));
s.start();
r.start();
}
//写
static class Sender implements Runnable {
Pipe.SinkChannel sinkChannel;
public Sender(Pipe pipe) {
sinkChannel = pipe.sink();
}
@Override
public void run() {
try {
ByteBuffer buf = ByteBuffer.allocate(1024);
buf.put("hello pipe".getBytes());
buf.flip();
sinkChannel.write(buf);
} catch (IOException e) {
e.printStackTrace();
}
}
}
//读
static class Recv implements Runnable {
Pipe.SourceChannel sourceChannel;
public Recv(Pipe pipe) {
sourceChannel = pipe.source();
}
@Override
public void run() {
try {
ByteBuffer buff = ByteBuffer.allocate(1024);
int len = sourceChannel.read(buff);
System.out.println(new String(buff.array(), 0, len));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}