1. Introduction to Basic concepts:
The first thing you need to do is briefly introduce UDP.
UDP The (User Datagram Protocol) protocol is a user datagram that, in the network, is used to process packets just like the TCP protocol. In the OSI model, the fourth layer, the transport layer, is in the upper layer of the IP protocol. It is a non-connected protocol, each datagram is a separate information, including the full source or destination address, it on the network with any possible path to the destination, so can reach the destination, the time to arrive at the destination and the correctness of the content is not guaranteed, but this protocol is convenient and fast, As a result, many communication tools and games still use this mode of communication, although sometimes there is a phenomenon of data drop frames.
( here can be simply understood as some of the unscrupulous courier agencies, because of a lack of responsibility, only responsible for sending as to whether the package can be smoothly delivered to the destination without concern, so there will be dropped packets or delayed reception phenomenon ).
Manipulating UDP in Java uses the Datagramsocket and Datagrampacket classes that are located under the java.net package in the JDK, making it very easy to control user data packets for UDP program development.
Use the Datagrampacket class in UDP development to wrap a message that needs to be sent, and then use the Datagramsocket class to complete the send operation of the information.
A complete UDP network development program consists of the server side and the client.
about the UDP The difference between a server and a client in development:
The only difference between client and server is that the server-side IP address and port are fixed, so the client can send the datagram directly to the server side, and the server side needs to determine the destination of the "feedback" datagram based on the datagram received.
The following is a brief introduction to the common methods of the Datagramsocket and Datagrampacket classes.
Datagramsocket class : Creating a socket instance that receives and sends UDP
Datagramsocket (): Creates an instance. Typically used for client-side programming, it does not have a specific listening port, just using a temporary one.
Datagramsocket (int port): Creates an instance and secures a message that listens on port ports.
Datagramsocket (int port, inetaddress localaddr): This is a very useful builder, when a machine has more than one IP address, the instance created by it only receives messages from LOCALADDR
Receive (Datagrampacket D): Receives data message to D. The Receive method produces a "blocking".
Send (Datagrampacket D): Send paper D to destination.
Setsotimeout (int timeout): Sets the time-out period in milliseconds.
Close (): Datagramsocket off. When an application exits, it usually releases the resource voluntarily, shutting down the socket, but may cause the resource not to be reclaimed due to an unexpected exit. Therefore, you should actively use this method to close the socket when the program completes, or to close the sock after catching the exception thrown
Note: 1. When creating an instance of the Datagramsocket class, if the port is already in use, a SocketException exception is thrown and the program terminates illegally, and the exception should be aware of the catch.
Datagrampacket class: for handling messages, wrapping data such as a byte array, destination address, destination port, etc. into a message or disassembling the message into a byte array.
Datagrampacket (byte[] buf, int length, inetaddress addr, int port): From the BUF array, take long data to create the packet object, the destination is the addr address, port ports.
Datagrampacket (byte[] buf, int offset, int length, inetaddress address, Intport): From the BUF array, take the length data from the offset start to create the packet object , the destination is the addr address, port.
Datagrampacket (byte[] buf, int offset, int length): Load data in the packet from offset, length long, into the BUF array.
Datagrampacket (byte[] buf, int length): The length of data in the packet is loaded into the BUF array.
GetData (): It obtains a byte array encoding of the message from the instance
2. Implementation method:
To implement a UDP program, it is recommended to first write from the client, specify the port to receive and obtain the data on the client.
Client (receive side) implementation steps
1. Set up a UDP socket service. To listen on a port. Datagramsocket ds = Newdatagramsocket (9001);
2. Define a buffer that encapsulates the buffer into the packet package. byte[] buf = new byte[1024];D atagrampacket dp = new Datagrampacket (buf,buf.length);
3. The data is stored in the packet via the socket's receive method. Ds.receive (DP);
4. Obtain the specified information in the package by means of the packet DP Method GetData (), getaddress (), Getport (), and so on.
5. Close the socket. Ds.close ();
Take a look at the following code for the UDP client program:
Import java.net.DatagramPacket; import Java.net.DatagramSocket; public class udpclient{public static void Main (String args[]) throws exception{ //All exceptions thrown datagramsocket ds = null; Defines the object that receives the datagram byte[] buf = new byte[1024]; Open space to receive data Datagrampacket DP = NULL; Declare Datagrampacket object ds = new Datagramsocket (9000); The client waits for the server to send information on port 9000 DP = new Datagrampacket (buf,1024);//All information used BUF save ds.receive (DP) ;//Receive Data string str = new String (Dp.getdata (), 0,dp.getlength ()) + "from" + dp.getaddress (). Gethostaddress () + ":" + DP. Getport (); System.out.println (str); Output content }};
After running the above program, the client program has opened the listening port, waiting for the server to send information to the client.
Here's the beginning of the server-side (send-side) implementation steps
1. Establish the Udpsocket service endpoint. The endpoint is established and the system randomly assigns a port. If you do not want to configure randomly, you can specify it manually. Datagramsocket ds = Newdatagramsocket (3000);
2. To encapsulate the data in a packet package, the destination address and port must be specified. byte[] buf = "Hi Red Army". GetBytes (); DATAGRAMPACKETDP =newdatagrampacket (Buf,buf.length,inetaddress.getbyname ("192.168.1.254"), 9000);
3. Send the packet through the Send method of the socket service. Ds.send (DP);
4. Close the socket service. The main is to close resources. Ds.close ();
The following begins to write the UDP send server program-udpserve
ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;Importjava.net.InetAddress; Public classudpserver{ Public Static voidMain (String args[])throwsexception{//all exceptions Throwndatagramsocket DS=NULL;//defining the objects that send datagramsDatagrampacket DP=NULL;//declaring Datagrampacket objectsDS=NewDatagramsocket (3000);//the server waits on port 3000 to send the message \String str= "Hello World!!!" ; DP=NewDatagrampacket (Str.getbytes (), Str.length (), Inetaddress.getbyname ("localhost"), 9000);//All information is saved using BUFSystem.out.println ("Send a message. ") ; Ds.send (DP); //send a message outDs.close (); }};
After the server-side program runs, the client can receive the data sent from the server side.
The above is a simple transceiver process. Of course, to ensure that each device can send and receive, you can run both the server and client programs.
From the above procedure we can see that when using Datagramsocket for network communication, the server side does not have to save the state of each client, the client sends the datagram to the server side, it is possible to exit immediately. However, the server cannot know the status of the client regardless of whether the client exits.
When using the UDP protocol, it is more difficult to have one client send chat messages forwarded to all other clients, consider using the set collection on the server side to hold all client information, and each time a client's datagram is received, The program checks whether the source socketaddress of the datagram is in the set collection, and if not, adds the socketaddress to the set collection. This also involves a problem: Some clients may send a datagram permanently after exiting the program, but the server side also saves the client's socketaddress in the Set collection ... In short, this way needs to deal with more problems, programming more cumbersome.
Based on the characteristics of UDP data transmission, its unreliability also brings us trouble in the development process, for such problems, the following solutions are proposed:
The server and client can establish a set of their own calibration scheme (many scenarios such as XML, checksum, etc.), if the data packet loss caused by incomplete data, the replacement of the form to complete, of course, this scheme is similar to the TCP handshake connection.
In the development process there are a lot of details, the article extracts some information on the network. Writing is not good, but also hope to forgive, this is a popular category of articles, hope to bring you help. If there is any problem found, please point out the convenience of my amendment. Thank you.
Zhang Jingyu
2015.3.15 in Nanjing Edition
Introduction to the principle mechanism and implementation of UDP in Java (recommended to read the reader before reading the basic knowledge of Java, a convenient understanding)