Java NIO中的DatagramChannel是一个能收发UDP包的通道。
操作步骤:
1.打开DatagramChannel
2.接受/发送数据
package com.expgiga.NIO; 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 { public void send() throws IOException { 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.put((new Date().toString() + ":\n" + str).getBytes()); buf.flip(); dc.send(buf, new InetSocketAddress("127.0.0.1", 9898)); buf.clear(); } dc.close(); } public void receive() throws IOException { DatagramChannel dc = DatagramChannel.open(); dc.configureBlocking(false); dc.bind(new InetSocketAddress(9898)); Selector sc = Selector.open(); dc.register(sc, SelectionKey.OP_READ); while (sc.select() > 0) { Iterator<SelectionKey> it = sc.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(); } } }
本文介绍如何使用 Java NIO 中的 DatagramChannel 进行 UDP 的非阻塞发送和接收操作。通过示例代码展示了 DatagramChannel 的基本用法,包括创建通道、配置为非阻塞模式、绑定端口、发送及接收数据。
723

被折叠的 条评论
为什么被折叠?



