Java NIO中的DatagramChannel是一个能收发UDP包的通道。
操作步骤:
  1)打开 DatagramChannel
  2)接收/发送数据

同样它也支持NIO的非阻塞模式操作,例如:

 @Test
public void send() throws IOException {
DatagramChannel channel = DatagramChannel.open();
channel.configureBlocking(false); ByteBuffer byteBuffer = ByteBuffer.allocate(1024); Scanner scanner = new Scanner(System.in);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
while (scanner.hasNext()) {
String line = scanner.next();
byteBuffer.put((format.format(new Date()) + ":" + line).getBytes());
byteBuffer.flip(); channel.send(byteBuffer, new InetSocketAddress("127.0.0.1", 9899));
byteBuffer.clear();
} channel.close();
} @Test
public void receive() throws IOException {
DatagramChannel channel = DatagramChannel.open();
channel.configureBlocking(false);
channel.bind(new InetSocketAddress(9899)); Selector selector = Selector.open();
channel.register(selector, SelectionKey.OP_READ); while (selector.select() > 0) {
Iterator<SelectionKey> selectionKeys = selector.selectedKeys().iterator();
while (selectionKeys.hasNext()) {
SelectionKey selectionKey = selectionKeys.next();
if (selectionKey.isReadable()) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
channel.receive(buffer);
buffer.flip();
System.out.println(new String(buffer.array(), 0, buffer.limit()));
buffer.clear();
} selectionKeys.remove();
}
} }
05-11 15:56