The output of the UDP protocol:
1 /*2 UDP sends data:3 A: Create A Socket send-side object4 B: Create a Datagram Package (package the data)5 C: Call the Socket object to send a datagram packet6 D: Freeing resources (underlying IO stream)7 */8 Public classNewsend {9 Ten Public Static voidMain (string[] args)throwsIOException { One A //A: Create A Socket send-side object -Datagramsocket ds =NewDatagramsocket (); - the //B: Create a Datagram Package (package the data) - //Public Datagrampacket (byte[] buf,int length,inetaddress address,int - //Port) - byte[] bys = "UDP send Data". GetBytes (); +Datagrampacket DP =NewDatagrampacket (bys, Bys.length, -Inetaddress.getbyname ("172.19.xx.xx"), 10010); + A //C: Call the Socket object to send a datagram packet at Ds.send (DP); - - //Freeing Resources - ds.close (); - } - in}
Receiving end:
1 /*2 UDP receives data:3 A: Creating A Socket Receive-side object4 B: Create a datagram package to receive data (Create Container)5 C: Call the Socket object's method to receive the datagram packet6 D: Parse packet (byte converted to string) and print in console7 E: Freeing Resources8 */9 Public classnewreceive {Ten One Public Static voidMain (string[] args)throwsIOException { A - //A: Creating A Socket Receive-side object -Datagramsocket ds =NewDatagramsocket (10010); the - //B: Create a datagram package to receive data (Create Container) - byte[] Bys =New byte[1000]; -Datagrampacket DP =NewDatagrampacket (bys,bys.length); + - //C: Call the Socket object's method to receive the datagram packet + Ds.receive (DP); A at //get IP on the send side -String IP =dp.getaddress (). GetHostName (); - //D: Parse packet (byte converted to string) and print in console -String s =NewString (Dp.getdata (), 0, Dp.getlength ()); - //Print to console -System.out.println (ip+ "--" +s); in - //Freeing Resources to ds.close (); + - the}
Code optimization of UDP protocol transmission for Java 25-4 Network programming