Content: A simple example of UDP communication.
Receiver:
public class Receiver {public static void main (string[] args) {Datagramsocket ds = null;try {//udp Receive-side ds = new Datagramsock ET (8080);//defines where UDP packets are received byte[] buf = new byte[1024];//defines the data receive packet for UDP datagrampacket DP = new Datagrampacket (buf, Buf.length); while (true) {//Receive packet ds.receive (DP); String string = new String (Dp.getdata (), 0, Dp.getlength ()); System.out.println ("Length:" + dp.getlength () + "+" + string);}} catch (SocketException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} finally {if (ds = null) ds. Close ();}}}
Sender:
public class Sender {public static void main (string[] args) {Datagramsocket ds = null;try {///defines a UDP socket to send data ds = new D Atagramsocket (); String Hello = "Hello world";//defines a UDP data sending packet to send data, inetsocketaddress represents the address to receive datagrampacket DP = new Datagrampacket ( Hello.getbytes (), hello.getbytes (). Length, New inetsocketaddress ("127.0.0.1", 8080)); for (int i = 0; i <; i++) {DS.S End (DP); Thread.Sleep (1000);}} catch (Exception e) {e.printstacktrace ();} finally {if (ds! = null) Ds.close ();}}}
Java Simple UDP Communication example