Using the UDP protocol to write a network program, set the receiver Terminal program listening port is 8001, the sender sends the data is "Hello, World".
Receiving end:
1 Importjava.net.*;2 Public classExample {3 4 Public Static voidMain (string[] args)throwsException5 {6 byte[] buf=New byte[1024];7Datagramsocket ds=NewDatagramsocket (8001);8Datagrampacket dp=NewDatagrampacket (buf,1024);9System.out.println ("Waiting to receive data");Ten Ds.receive (DP); OneString str=NewString (Dp.getdata ()); A System.out.println (str); - ds.close (); - } the -}
Send side:
1 Importjava.net.*; 2 Public classexample1 {3 4 Public Static voidMain (string[] args)throwsexception{5Datagramsocket ds=NewDatagramsocket (3000); 6String str= "Hello, World"; 7Datagrampacket dp=NewDatagrampacket (Str.getbytes (), Str.length (), Inetaddress.getbyname ("localhost"), 8001);8SYSTEM.OUT.PRINTLN ("Send Message"); 9 Ds.send (DP); Ten Ds.close (); One } A}
Operation Result:
Java UDP Protocol Transport