the Datagramchannel in Java NIO is a channel that can send and receive UDP packets.
Operation Steps:
1) Open Datagramchannel
2) receive / send data
It also supports NIO's non-blocking mode operations, such as:
1 @Test2 Public voidSend ()throwsIOException {3Datagramchannel channel =Datagramchannel.open ();4Channel.configureblocking (false);5 6Bytebuffer Bytebuffer = bytebuffer.allocate (1024);7 8Scanner Scanner =NewScanner (system.in);9SimpleDateFormat format =NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");Ten while(Scanner.hasnext ()) { OneString line =Scanner.next (); ABytebuffer.put ((Format.format (NewDate ()) + ":" +Line ). GetBytes ()); - Bytebuffer.flip (); - theChannel.send (Bytebuffer,NewInetsocketaddress ("127.0.0.1", 9899)); - bytebuffer.clear (); - } - + channel.close (); - } + A @Test at Public voidReceive ()throwsIOException { -Datagramchannel channel =Datagramchannel.open (); -Channel.configureblocking (false); -Channel.bind (NewInetsocketaddress (9899)); - -Selector Selector =Selector.open (); in Channel.register (selector, selectionkey.op_read); - to while(Selector.select () > 0) { +Iterator<selectionkey> Selectionkeys =Selector.selectedkeys (). iterator (); - while(Selectionkeys.hasnext ()) { theSelectionkey Selectionkey =Selectionkeys.next (); * if(Selectionkey.isreadable ()) { $Bytebuffer buffer = bytebuffer.allocate (1024);Panax Notoginseng channel.receive (buffer); - Buffer.flip (); theSystem.out.println (NewString (Buffer.array (), 0, Buffer.limit ())); + buffer.clear (); A } the + Selectionkeys.remove (); - } $ } $ -}
Java-nio (eight): Datagramchannel