The UDP protocol is non-connection-oriented and is more efficient than the TCP protocol, but not secure. UDP protocol is similar to the process of sending information, whether the receiver is online or shutdown state, will send the information. However, if the receiver is not in the state of receiving information, the packets sent out will be lost.
The convert () method is used to transform the byte array and the base type.
/** * Create UDP protocol-based service receiver * @author Wxisme * */public class MyServer {public static void main (string[] args) throws Ioexceptio n {//Create service-side port Datagramsocket Server = new Datagramsocket (9898);//container ready to accept data byte[] container = new byte[1024];// Encapsulate data into packet datagrampacket packet = new Datagrampacket (container, container.length);//Receive Data server.receive (packet);//Analysis data/ /byte[] data = Packet.getdata ();d ouble data = convert (Packet.getdata ()); int len = Packet.getlength ();// System.out.println (new String (data, 0, Len)); SYSTEM.OUT.PRINTLN (data);//Release Resources server.close ();} /** * Convert to Basic type * @param data * @return * @throws ioexception */public static double convert (byte[] data) throws Ioexcep tion {datainputstream dis = new DataInputStream (new Bytearrayinputstream (data));d ouble num = dis.readdouble (); return num ;}}
/** * Create UDP protocol-based customer send data end * @author wxisme */public class MyClient {public static void main (string[] args) throws Ioexceptio n {//Create server port Datagramsocket client = new Datagramsocket (6868);//Prepare data//string str = "UDP Protocol";d ouble num = 216.35;//byt e[] data = Str.getbytes (); byte[] data = CONVERT (num);//Data packaging Datagrampacket packet = new Datagrampacket (data, Data.length, n ew inetsocketaddress ("localhost", 9898));//Send Data client.send (packet);//Close Resource client.close (); System.exit (0);} /** * Convert base type to byte array * @param num * @return * @throws ioexception */public static byte[] CONVERT (double num) throws Ioex ception {byte[] data = null; Bytearrayoutputstream BOS = new Bytearrayoutputstream ();D ataoutputstream dos = new DataOutputStream (BOS); Dos.writedouble (num);d os.flush ();d ata = Bos.tobytearray ();d os.close (); return data;}}
The basic principle and simple usage of UDP protocol in Java