Java NIO中的DatagramChannel是一个能收发UDP包的通道。
操作步骤:
1)打开 DatagramChannel
2)接收/发送数据
同样它也支持NIO的非阻塞模式操作,例如:
public static void main(String[] args){ new Thread(new Runnable() { @Override public void run() { server(); } }).start(); new Thread(new Runnable() { @Override public void run() { client(); } }).start(); } // udp,非阻塞io,客户端 public static void client(){ DatagramChannel datagramChannel = null; try { // 1.获取通道 datagramChannel = DatagramChannel.open(); // 2.置为非阻塞模式 datagramChannel.configureBlocking(false); // 3.分配缓冲区 ByteBuffer byteBuffer = ByteBuffer.allocate(1024); while (true) { Thread.sleep(3000); // 4.向缓冲区放数据 byteBuffer.put(("时间:"+CommonUtil.getDateTime()+",编号:"+UUID.randomUUID().toString()).getBytes()); byteBuffer.flip(); // 5.通道向服务端发送 datagramChannel.send(byteBuffer, new InetSocketAddress("127.0.0.1", 2787)); byteBuffer.clear(); } } catch (Exception ex) { ex.printStackTrace(); } finally{ if (datagramChannel!=null) { try { datagramChannel.close(); } catch (IOException ex) { ex.printStackTrace(); } } } } // udp,非阻塞io,服务端 public static void server(){ DatagramChannel datagramChannel = null; try { // 1.获取通道 datagramChannel = DatagramChannel.open(); // 2.置为非阻塞模式 datagramChannel.configureBlocking(false); // 3.绑定监听端口 datagramChannel.bind(new InetSocketAddress(2787)); // 4.获取选择器 Selector selector = Selector.open(); // 5.通道注册选择器 datagramChannel.register(selector, SelectionKey.OP_READ); // 5.获取选择器上的已选择的键 while (selector.select()>0) { Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey skey = it.next(); // 7.判断当前键的监听事件 if (skey.isConnectable()) { System.out.println("connectable"); }else if (skey.isAcceptable()) { System.out.println("acceptable"); }else if (skey.isReadable()) { System.out.println("readable"); ByteBuffer mBuffer = ByteBuffer.allocate(1024); datagramChannel.receive(mBuffer); mBuffer.flip(); System.out.println("receive:"+new String(mBuffer.array(), 0, mBuffer.array().length)); mBuffer.clear(); } } it.remove(); } } catch (Exception ex) { ex.printStackTrace(); } finally{ if (datagramChannel!=null) { try { datagramChannel.close(); } catch (IOException ex) { ex.printStackTrace(); } } } }
结果
readable receive:时间:2017-01-01 19:01:46,编号:63feeb8f-7ead-4e2f-a65b-8471ef3940e3 readable receive:时间:2017-01-01 19:01:46,编号:63feeb8f-7ead-4e2f-a65b-8471ef3940e4 readable receive:时间:2017-01-01 19:01:46,编号:63feeb8f-7ead-4e2f-a65b-8471ef3940e5 readable receive:时间:2017-01-01 19:01:46,编号:63feeb8f-7ead-4e2f-a65b-8471ef3940e6