The following is a sample code for the UDP base level:
First, we understand the idea of creating a UDP transmission:
1. Create a UDP socket service.
2. Encapsulate the data that will be sent into the packet.
3. Send the data packets through the UDP socket service.
4. Close the socket service.
And the idea of receiving end is as follows:
1. Create a UDP socket service. You need to specify a port number.
2. Create a packet that stores the received data and facilitates the resolution of various data using the method of the Packet object.
3. Use the Recive method of the socket service to store the received data in a packet.
4. Parse the data in the packet through the methods in the packet.
5. Close the resource.
The specific code is as follows:
Send Side
public class Udpsenddemo {
public static void Main (string[] args) throws IOException {
System.out.println ("Send side start .....") ");
1. UDP socket service, using the Datagramsocket object, you can specify a port to send, or the server will select an unused port by default
Datagramsocket da = new Datagramsocket (9999);
2. Encapsulates the data that will be sent into a packet. Use Datagrampacket to encapsulate the sending data inside
String str= "UD sends data demo";
Byte[] Buf=str.getbytes ();
Defines the IP address and port of the receiver
Datagrampacket dp= New Datagrampacket (buf, Buf.length,inetaddress.getbyname ("192.168.5.163"), 10000);
3. Send the Datagrampacket data packets via the UDP socket service, using the Send method
Da.send (DP);
4. Close resources when resources are used
Da.close ();
}
}
Receiving end
public class Udprecivedemo {
public static void Main (string[] args) throws IOException {
System.out.println ("Receive Side start ... ");
1. Create a UDP socket service.
Datagramsocket ds = new Datagramsocket (10000);
2. Create a received Packet
Byte[] Buf=new byte[1024];
Datagrampacket DP = new Datagrampacket (buf, buf.length);
3. Use the Recive method of the socket service to store the received data in a packet.
Ds.receive (DP);
4. Parse the data in the packet through the methods in the data object. For example: IP address, port, content
String ipstring=dp.getaddress (). gethostaddress ();
int port =dp.getport ();
String Data= new String (Dp.getdata (), 0,dp.getlength ());
System.out.println ("IP:" +ipstring+ "\ n" + "Port:" +port+ "\ n" + "data:" +data);
5. Close Resources
Ds.close ();
}
}
Java Network Programming (ii)----example of a UDP base level