Java Network Programming-udp

Source: Internet
Author: User
Tags time in milliseconds

When using the UDP protocol, we usually use other language tools to complete the work. So today we will mainly introduce the use of UDP protocol in Java. First, let's take a look at the basic concepts of UDP. The full name of UDP protocol is user datagram, which is used to process data packets in the same way as TCP protocol in the network. In the OSI model, in the layer-4 ?? Transport layer, which is on the top of the IP protocol. UDP has the disadvantages of not providing packet grouping, assembly, and not sorting data packets. That is to say, when a packet is sent, it is impossible to know whether it is safe and complete 。

Why UDP?

When choosing to use the Protocol, you must be cautious when choosing UDP. in an environment with unsatisfactory network quality, UDP packet loss may be serious. However, due to the characteristics of UDP: it is not a connection protocol, so it has the advantages of low resource consumption and high processing speed. Therefore, most of the audio, video, and common data are transmitted using UDP, because even if one or two packets are occasionally lost, they do not have much impact on the received results. For example, the ICQ and OICQ used in our chat are the UDP protocol 。

Manipulating UDP in Java

You can use the initramsocket and initrampacket classes under the java.net package in JDK to conveniently control user data packets 。

Before describing them, you must understand the inetaddress class in the same location. inetaddress implements Java. io. the serializable interface does not allow inheritance. It is used to describe and package an Internet IP address and returns an inetaddress instance in three ways:

Getlocalhost (): returns the instance that encapsulates the local address 。

Getallbyname (string host): returns an array of inetaddress instances that encapsulate the host address 。

Getbyname (string host): returns an instance that encapsulates the host address. The host can be a domain name or a valid IP address 。

The initramsocket class is used to create a socket instance for receiving and sending UDP protocols. It is the same as the socket class that relies on the socketimpl class, the implementation of the initramsocket class also relies on the initramscoketimplfactory class specifically designed for it. The initramsocket class has three constructors:

Datagramsocket (): creates an instance. This is a special usage and is usually used for client programming. It does not have a specific listening port and only uses a temporary one 。

Datagramsocket (INT port): creates an instance and keeps listening to port packets 。

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 packets from localaddr 。

It is worth noting that when creating an initramsocket class instance, if the port has been used, a socketexception exception will be thrown and the program is terminated illegally, this exception should be captured. The main methods of the datagramsocket class include four:

Receive (datagrampacket D): receives data packets to D. The receive method produces a "blocking "。

Send (datagrampacket D): send the message D to the destination 。

Setsotimeout (INT timeout): Set the timeout time in milliseconds 。

Close (): Close mongoramsocket. When the application exits, resources are usually released and the socket is closed. However, resources cannot be recycled due to abnormal exit, when the program is completed, you should take the initiative to use this method to close the socket, or close the socket after an exception is caught 。

"Blocking" is a specialized term that produces an internal loop that pauses the program in this place until a condition is triggered 。

The datagrampacket class is used to process packets. It packs data such as the byte array, target address, and target port into a packet or disassembles the packet into a byte array. The application should note that, TCP/IP requires a maximum of 65507 data packets. Generally, the host receives 548 bytes, but most platforms can support 8192 bytes of packets. There are a total of four builders of the datagrampacket class:

Datagrampacket (byte [] Buf, int length, inetaddress ADDR, int port): Extracts long length data from the Buf array to create a data packet object. The target is the ADDR address and port 。

Datagrampacket (byte [] Buf, int offset, int length, inetaddress address, int port): extracts data packet objects with a long length starting with offset from the Buf array, the target is the ADDR address and port 。

Datagrampacket (byte [] Buf, int offset, int length): pack the data starting from offset and length into the Buf array 。

Datagrampacket (byte [] Buf, int length): load the data with length in the data packet into the Buf array 。

The most important method of the datagrampacket class is getdata (), which obtains the byte array encoding of packets from the instance 。

Simple examples of UDP protocol

 
 
  1. {Server receiving data}
  2. Byte[] Buf =New Byte[1000];
  3. Datagramsocket DS =NewDatagramsocket (12345); // start monitoring port 12345
  4. Datagrampacket IP =NewDatagrampacket (BUF, Buf. Length); // create an instance that receives the datagram
  5. While(True)
  6. {Ds. Receive (IP); // blocking until the data is loaded into the IP address after receiving the datagram
  7. System. Out. println (NewString (BUF ));}
  8. {Client sending data}
  9. Inetaddress target = inetaddress. getbyname ("www.xxx.com"); // obtain the address instance of the target machine
  10. Datagramsocket DS =NewDatagramsocket (9999); // send a datagram from port 9999
  11. String Hello = "Hello, I am comeIn! "; // Data to be sent
  12. Byte[] Buf = Hello. getbytes (); // convert data to byte type
  13. OP =NewDatagrampacket (BUF, Buf. length, target, 12345); // package data in the Buf Buffer
  14. DS. Send (OP); // send data
  15. DS. Close (); // close the connection
Related Article

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.