1. Basic Concepts:
A.datagrampacket and Datagramsocket are located in the java.net package
B.datagrampacket represents a datagram that holds data, datagramsocket a socket that accepts or sends datagrams.
C. All network links made up of these two classes are based on UDP protocol and are an unreliable protocol.
The reason is unreliable because the sender is not responsible for the success of the data sent, the receiver will not receive data to the sender Feedback success message, easy to lead to loss of information.
But this protocol is fast, such as CS (Half Life) game is based on UDP protocol, otherwise we would like to play a game after the machine will be smashed, so we can see the game is sometimes lost frame.
2. How to use:
To establish a link based on the UDP protocol, we should first establish the socket <DatagramSocket> (i.e., the sending station or the receiving terminal), then send or receive data <DatagramPacket> via the socket.
Let's take a look at the Datagramsocket and Datagrampacket classes.
Datagramsocket class:
Construction Method:
Datagramsocket ():
Represents the creation of a default socket and binding to a local address and a random port number
Datagramsocket (int port):
Unlike the above, binding to a specific port number, the other invariant
Datagramsocket (int port, inetaddress iad):
Represents creating a socket, binding to a specific port number, and specifying an address
Datagramsocket (socketaddress sad);
Represents the creation of a socket, bound to a specific socket address
Small hint: the so-called local address we can understand that we can see through the "Control Panel-local connection-support" of an IP address, this is the local IP address, but also for the moment to understand the local address.
Basic methods:
Close ():
Close socket
Recevie (Datagrampacket dp):
Accept Datagram
Send (Datagrampacket DP):