Java Network programming: UDP communication __ Algorithm

Source: Internet
Author: User
Tags server port

Network communication In addition to the way the TCP, there is a way to implement the UDP way. UDP (user Datagram Protocol), the Chinese meaning is the Customer datagram protocol, similar to send short message, is a cheap way of communication, use this way without establishing a dedicated virtual connection, because no need to establish a dedicated connection, so the pressure on the server is much smaller than TCP , so it is also a common way of network programming. But the biggest disadvantage of using this approach is that transmission is unreliable, of course, is not to say that often lost, as we send short messages, the theoretical existence of the possibility of not receiving, this is likely to be 1%, anyway relatively small, but due to this possible existence, so usually we feel that the important thing is to make a phone call ( Similar to the TCP way), the general thing to send short messages (similar to the UDP method). Network programming is also the case, must require reliable transmission of information generally using TCP, the general data to use the UDP method to achieve.

The UDP network programming also obtains the good support in the Java language, because it does not need to establish the special connection and so on in the transmission data the process, therefore the implementation structure which in the Java API design and the TCP method is not very same. Of course, the class that needs to be used is included in the java.net package.

In the Java API, the implementation of UDP programming, including client network programming and server-side network programming, is mainly implemented by two classes, respectively:

L Datagramsocket

The Datagramsocket class implements network connections, including client network connections and server-side network connections. Although UDP network communication does not need to establish a dedicated network connection, but still need to send and receive data, Datagramsocket is the transmitter to send data, as well as the role of the listener when receiving data. Analogous to a network connection in TCP, this class can be used either to implement a client connection or to implement a server-side connection.

L Datagrampacket

The Datagrampacket class implements the encapsulation of data that is transmitted over the network, that is, the object of the class represents the data exchanged in the network. In UDP network programming, both the data to be sent and the data to be received must be processed into a Datagrampacket type object that contains the address sent to, the port number sent to, and the content sent. In fact, the role of the Datagrampacket class is similar to the actual letter in the letter, including the letter sent to the address and receiver, as well as the content sent, the post office only need to be delivered by address. When receiving data, the received data must also be processed into an object of type Datagrampacket, containing information such as the sender's address, port number, and the contents of the data. Compared with TCP network transmission, IO programming is not a necessary content in UDP network programming, and the structure is simpler than that of TCP mode network programming.

The following describes the UDP way of network programming, the client and server-side implementation steps, as well as through the basic example of the UDP way of network programming in the Java language to implement the way.

UDP network programming, programming steps and TCP similar, but the use of classes and methods exist a relatively large difference, the following first introduction to the UDP network programming client implementation process.

The steps involved in UDP client programming are also 4 parts: establishing a connection, sending data, receiving data, and closing a connection.

This paper first introduces the implementation of the connection in the network programming of UDP mode. The UDP way of establishing a connection and TCP mode is different, only need to establish a connection object, you do not need to specify the server's IP and port number. The implemented code is:

Datagramsocket ds = new Datagramsocket ();

This establishes a client connection that uses the unused port number of one local computer that is randomly assigned by the system. In this connection, the server-side IP and port are not specified, so the UDP network connection is more like a transmitter than a specific connection.

Of course, you can create a client connection by setting the port number used by the connection.

Datagramsocket ds = new Datagramsocket (5000);

This creates a connection using port No. 5000 on the local computer. Typically, there is no need to specify a port number when establishing a client connection.

Next, introduce the implementation of sending data in UDP client programming. In the UDP network programming, IO technology is not necessary, when sending data, the need to send the data content first converted to a byte array, and then the data content, server IP and server port number together to construct a Datagrampacket type of object, This completes the preparation of the data, which can be sent by calling the Send method in the network connection object when it is sent. For example, to send the string "Hello" to the IP is 127.0.0.1, the port number is 10001 of the server, the implementation of the code to send data is as follows:

String s = "Hello";

String host = "127.0.0.1";

int port = 10001;

Converts the sent content to a byte array

Byte[] B = s.getbytes ();

Convert server IP to inetaddress object

InetAddress Server = Inetaddress.getbyname (host);

Constructs a sent packet object

Datagrampacket SENDDP = new Datagrampacket (b,b.length,server,port);

Send data

Ds.send (SENDDP);

In this example code, regardless of what the data is sent, it needs to be converted to a byte array, and then the server-side IP address is constructed into an object of type inetaddress, which is constructed as a Datagrampacket type object after the preparation is complete, In UDP programming, the data content sent, server-side IP, and port number are included in the Datagrampacket object. When you are ready to do so, call the Send method of the connection object DS to send the Datagrampacket object.

In accordance with the Protocol of UDP, in the data transmission, the system is only to do their best to transmit data, but does not guarantee that the data must be transmitted correctly, if the data lost in the transmission process, it is lost.

UDP in the network communication, but also follow the "request-response" model, after sending data is completed, you can receive server-side feedback data.

The following describes the implementation of receiving data in UDP client programming. When the data is sent out, you can receive feedback from the server side. Receiving data is implemented in the Java language by first constructing a data buffer array that is used to store received server-side feedback data that must be greater than or equal to the length of the actual valid data for server-side feedback. A Datagrampacket packet object is then constructed based on the buffer array, and the receiving method of the connection object is finally invoked to receive the data. The received server-side feedback data is stored inside the object of the Datagrampacket type. The sample code that implements the receive data and displays server-side feedback is as follows:

Constructing buffer arrays

byte[] data = new byte[1024];

Constructing a Packet object

Datagrampacket received = new Datagrampacket (data,data.length);

Receive data

Ds.receive (RECEIVEDP);

Output data content

Byte[] B = receivedp.getdata (); Get buffer Array

int len = Receivedp.getlength (); Get Valid data Lengths

string s = new string (B,0,len);

System.out.println (s);

In this code, first, the buffer array data is constructed, where the length 1024 is the estimated length of the received data, requiring that the length must be greater than or equal to the received data length, then construct the packet object based on the buffer array, and receive the feedback data using the Receive method of the connection object DS. Because in the Java language, objects other than string are delivered by address, the contents of the packet object RECEIVEDP can be changed within the Receive method, where the function and return value of the RECEIVEDP are similar. When the data is received, it is only necessary to read it from the packet object, using the GetData method in the Datagrampacket object to obtain a buffer array of the packet object, but the length of the buffer array is generally greater than the length of the valid data, in other words, That is, only a subset of the data in the buffer array is feedback data, so it is necessary to use the GetLength method in the Datagrampacket object to obtain the length of valid data, then the valid data is the content of the former valid data length in the buffer array, which is the content of the real server-side feedback data.

The last step in UDP-mode client network programming is to close the connection. Although the UDP method does not establish a dedicated virtual connection, the connection object still requires system resources, so the connection must be closed after the use is complete. Closing the connection uses the Close method in the connection object to implement the following code:

Ds.close ();

It should be explained that, and TCP to establish a connection in different ways, UDP way of the same network connection object, can send to different server-side IP or port packets, this is not the way TCP.

After introducing the basic knowledge of the UDP mode client network programming, the following is a brief introduction to the basic knowledge of UDP server-side network programming.

UDP network programming server-side implementation and TCP way of server-side implementation is similar to the server to listen to a certain port, and then get the packet, logic processing will be processed after the results of feedback to the client, and finally shut down the network connection, the following in turn to introduce.

First UDP server-side network programming needs to establish a connection, the connection listens to a port, the implementation of the code is:

Datagramsocket ds = new Datagramsocket (10010);

Because server-side ports need to be fixed, the port number is typically specified when a server-side connection is established. For example, the example code specifies that port number 10010 is used on the server side, and the client side connects the port number when connecting to the server side.

Then the server will begin to receive the data sent by the client, the method of reception and the method of receiving the client have been, in which the effect of the Receive method is similar to that of the Accept method in the TCP mode, which is also a blocking method, and its function is to receive the data.

After receiving the data that the client sent over, the server side of the data to the logical processing, and then the processing of the results are sent to the client, where to send a bit more trouble than the client, because the server side needs to obtain the client's IP and client-side use of the port number, which can be obtained from the packet received. The sample code is as follows:

Get the IP of the client

InetAddress ClientIP = receivedp.getaddress ();

Get the client's port number

Int clientport = Receivedp.getport ();

Using the code above, you can obtain the client's IP address and the client's port number from the received packet object RECEIVEDP, so that the processed data can be constructed into a packet object on the server side, and then the processed data content is fed back to the client.

Finally, when the server-side implementation is complete, the server-side connection is turned off to call the Close method of the Connection object, as shown in the sample code:

Ds.close ();

After introducing the basic knowledge of client programming and server-side programming in UDP, the following is a simple example to demonstrate the basic use of UDP network programming.

The function of this example is to implement the system time of the client program to the server side, the server side receives the time, to the client feedback string "OK". The client code that implements this feature looks like this:

Package UDP;

Import java.net.*;
Import java.util.*;
/**
 * Simple UDP client, realize system time function to server side/public
class Simpleudpclient {public
            static void Main (string[) args) {

                     datagramsocket ds = NULL;//Connection object

                     Datagrampacket SENDDP;//Send Packet object

                datagrampacket RECEIVEDP;// Receive Packet object

                     String serverhost = "127.0.0.1";

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.