UDP for network communication programming in Java programming

Source: Internet
Author: User
Tags server port

In the last article we discussed the specific use of TCP and its differences with UDP, this time we talk about the actual application of Java network programming in UDP.

UDP Programming

UDP English User Datagram Protocol, Chinese meaning is User Datagram protocol. The UDP protocol does not need to establish a dedicated virtual connection during file transfer. So this protocol on the server is relatively small, but the lack of UDP is that it belongs to unreliable transmission, but it is not as reliable as we think, as I send you text messages, in theory, there is the possibility that you can not receive.

UDP programming in Java has client network programming and server-side network programming two implementations.

Datagramsocket

Datagramsocket is similar to TCP network connectivity, although UDP does not need to establish a dedicated virtual connection, but after all, is to send and accept data, Datagramsocket can implement the server's listener and the sender role of the transmitter.

Datagrampacket

Datagrampacket is analogous to data encapsulation in a network, meaning that the object of this class represents the data to be transferred. When data is transmitted, the class encapsulates the data, and the encapsulated object contains the IP address of the target, the port number, and the content being sent. Accept the data is also the way to receive the Datagramsocket object, the data received contains the sender's IP port information, of course, also contains the content sent over. Image Point said, Datagramsocket object is like a courier, Mail courier when there is a variety of information on the receiving side, the envelope has content.

In summary, UDP is programmed in Java in a simpler way than the TCP structure.

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

1, establish the connection

Datagramsocket ds = new Datagramsocket ();

This client connection uses the unused port number of a local computer that is randomly assigned by the system
Of course, you can create a client connection by setting the port number used by the connection.
Datagramsocket ds = new Datagramsocket (5000);

Typically, there is no need to specify a port number when establishing a client connection.

2, send data

When sending data, you need to convert the data content that needs to be sent first to a byte array, and then construct the data content, server IP, and server port number together into a Datagrampacket type object, so that the data is ready to complete, Send this object by calling the Send method in the network connection object at send

String host = "127.0.0.1";  
    int port = 10001;  
   Converts the sent content to byte array  
    byte[] b = s.getbytes ();  
    Convert server IP to inetaddress object  
    inetaddress Server = inetaddress.getbyname (host);  
    Constructs the sent packet object  
    datagrampacket SENDDP = new Datagrampacket (b,b.length,server,port);  
    Send data  
    ds.send (SENDDP);</span>  


Before sending the data, we must encapsulate the data to be sent.
3, the service side accept the data

First, you construct 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

byte[] data = new byte[1024];  
    Constructs the Packet object  
    datagrampacket RECEIVEDP = 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 length  
    String s = new S Tring (B,0,len);  
    System.out.println (s);</span>  


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.
4, close the connection

Ds.close ();

UDP mode server-side network programming

1, first UDP way server-side network programming needs to establish a connection, which listens to a port:
Datagramsocket ds = new Datagramsocket (10010);
Because the server-side ports need to be fixed, the port number is typically specified when a server-side connection is established
2. Receive the data sent by the client
The method of receiving and the method of receiving the client has been, in which the function of the Receive method is similar to that of the Accept method in TCP mode, which is also a blocking method, which is used to receive data.
Ds.receive ()
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:

     Obtain the client IP
     inetaddress clientip = receivedp.getaddress ();
     Get the client's port number
     Int ClientPort = Receivedp.getport ();


3, close the connection
Ds.close ()

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.