The Datagramchannel in Java NiO is a channel that can send and receive UDP packets. Because UDP is a non-connected network protocol, it cannot be read and written like other channels. It sends and receives a packet.
Server-side code
Package Com.test.nio;import Java.io.ioexception;import Java.net.inetsocketaddress;import java.nio.ByteBuffer; Import Java.nio.channels.datagramchannel;public class Testudpserver {/** * @param args * @throws Exception */public s tatic void Main (string[] args) throws Exception {Datagramchannel channel=datagramchannel.open (); Channel.socket (). bind (New Inetsocketaddress (9999)); Bytebuffer buf=bytebuffer.allocate, Buf.clear ();/* Blocking, waiting for data */channel.receive (BUF);/* Set buffer readable */buf.flip ();/* Loop read out all characters */while (buf.hasremaining ()) {System.out.print ((char) buf.get ());}}}
Client code
Package Com.test.nio;import Java.io.ioexception;import Java.net.inetsocketaddress;import java.nio.ByteBuffer; Import Java.nio.channels.datagramchannel;public class Testudpclient {/** * @param args * @throws Exception */public s tatic void Main (string[] args) throws Exception {Datagramchannel channel=datagramchannel.open (); String newdata= "hello,itbuluoge!" +system.currenttimemillis (); Bytebuffer buf=bytebuffer.allocate (buf.clear); Buf.put (Newdata.getbytes ()); Buf.flip ();/* Send UDP packets */int Bytessent=channel.send (buf, New inetsocketaddress ("127.0.0.1", 9999));}}
Output results
In fact, the above code function is very simple, that is, the server listens, the client sends a UDP packet, if the server is not listening or has been shut down, the client sends will not throw an exception, because UDP is a non-connection-oriented protocol.
The UDP usage of NIO in Java