UDP is mainly used in Java Datagramsocket to achieve communication, data is generally encapsulated through datagrampacket;
The sender only needs to specify the address and port of the receiver, and then through the Send () method can be encapsulated in the Datagrampacket data sent past!
The receiver only needs to use the same datagramsocket and a datagrampacket to receive the data, accept just specify the port to accept, as follows:
Sender:
Packagecom.seven.exercise1;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;Importjava.net.InetAddress; Public classUdpsend { Public Static voidMain (string[] args)throwsException {//1.UDP ServiceDatagramsocket ds =NewDatagramsocket (); //2. Encapsulating data to Datagrampacket byte[] data = "Hello UDP socket". GetBytes (); InetAddress inetaddress= Inetaddress.getbyname ("127.0.0.1");//address.Datagrampacket Datagrampacket =NewDatagrampacket (data, Data.length, InetAddress, 10000); //3. Send Datads.send (Datagrampacket); //4. CloseDs.close (); }}
The receiving party;
Packagecom.seven.exercise1;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket; Public classudpreceive { Public Static voidMain (string[] args)throwsexception{//1. Create a new receiving partyDatagramsocket Datagramsocket =NewDatagramsocket (10000); //2. Bind to receive package byte[] B =New byte[1024]; Datagrampacket DP=NewDatagrampacket (b,b.length); //3. Receiving DataDatagramsocket.receive (DP); //4. If you receive the data, print it out.String data =NewString (Dp.getdata (), 0, Dp.getlength ()); System.out.println (Dp.getaddress (). Gethostaddress ()+ "----->" +data); //5. Close;Datagramsocket.close (); }}
Because UDP is non-connected, so no matter how to run can, but in order to be able to accept the data, we have to run the receiver first, then to run the sender, so as to see the effect, otherwise the packet loss will not see what the effect of = =.
Java Network Programming (3)--UDP