UDP is a high-speed, connectionless method of data interchange, characterized by even if the receiver is not connected (and not allowed to connect), the recipient can also send the packet, just as in a multiple-user walkie-talkie environment, you do not know if your information is accepted by the person you need, but your information is actually passed and disappeared. Sometimes speed is more important than data integrity, and it is acceptable to lose a few frames in a video conference. However, it is not applicable in environments where data security is required.
Send step: Use Datagramsocket (int port) to establish the socket (en suite word) service. Package data in Datagrampacket to send (send () method) close resources through the socket service
Import java.io.IOException;
Import java.net.*;
public class Send {public
static void Main (string[] args) {
Datagramsocket ds = null; Set up the suite character Udpsocket service
try {
ds = new Datagramsocket (8999); Instantiate the suite word, specifying its own port
} catch (SocketException e) {
System.out.println ("Cannot open port!");
System.exit (1);
}
Byte[] buf= "Hello, I am sender!". GetBytes (); Data
inetaddress destination = null;
try {
destination = Inetaddress.getbyname ("192.168.1.5"); Address to be sent
(Unknownhostexception e) {
System.out.println ("Cannot open findhost!");
System.exit (1);
}
Datagrampacket DP =
new Datagrampacket (buf, buf.length, Destination, 10000);
Package into the Datagrampacket type (the Datagramsocket send () method accepts this class, noting that 10000 is the port that accepts the address, unlike its own port.
try {
ds.send (DP); Send data
} catch (IOException e) {
}
ds.close ();
}
Receive step:
Use Datagramsocket (int port) to create a socket (en suite word) service. (We note that this service can be received and sent), and port specifies the monitoring acceptance port. Define a packet (Datagrampacket), store received data, use the method to extract the transmitted content through the Datagramsocket receive method to deposit the received data into the defined package using the Datagrampacket method, Extract the data. Closes the resource.
Import java.net.*;
public class Rec {public
static void Main (string[] args) throws Exception {
Datagramsocket ds = new Datagramsocke T (10000); Define service, monitor port above the send port, note not send itself Port
byte[] buf = new byte[1024];//Accept content size, note do not overflow
datagrampacket dp = new Datagrampacket (buf,0,buf.length);//define a received package
ds.receive (DP);//package accepted content into package
String data = new String ( Dp.getdata (), 0, Dp.getlength ());//Use GetData () method to extract content
System.out.println (data);//print Content
ds.close ();//Close Resource
}
}