A preliminary study of Datagrampacket and Datagramsocket in Java

Source: Internet
Author: User

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):

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.