JavaSE-UDP protocol network programming (2), javaseudp

Source: Internet
Author: User
Tags time in milliseconds

JavaSE-UDP protocol network programming (2), javaseudp

In UDP network programming, the sender has no connection with the receiver, and there is no obvious difference between the server and the client.

  • Class DatagramSocket:

This class indicates the socket used to send and receive the datagram packet.

Main constructor methods:

DatagramSocket (): creates an instance, binds the default IP address of the local machine, and randomly selects a port. It is usually used for client programming. There is no specific listening port and only a temporary one is used.
DatagramSocket (int port): creates an instance and specifies the Port number, that is, fixed listening port packets.
DatagramSocket (int port, InetAddress localAddr): Specifies the IP address and port number. When a machine has more than one IP address, the instance it creates only receives packets from LocalAddr.

Common Methods:

Receive (DatagramPacket d): receives data packets to d.
Send (DatagramPacket d): send the message d to the destination.
SetSoTimeout (int timeout): Set the timeout time in milliseconds.
Close (): close DatagramSocket. When an application exits, resources are usually automatically released and the Socket is closed. However, resources cannot be recycled due to abnormal exit. Therefore, you should take the initiative to use this method to close the Socket when the program is completed, or close the Sock after an exception is caught and thrown.

  • DatagramPacket:

It is used to process packets, package data such as byte array, target address, and target port into packets, or disassemble the packets into byte arrays.

Main construction method:

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 the data packet object with 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 data starting from offset and long length into the buf array.
DatagramPacket (byte [] buf, int length): load the data with length in the data packet into the buf array.

Common Methods:

GetData (): it obtains the byte array encoding of packets from the instance.

  • Send and accept UDP datagram

Sender:
1. Create a udpsocket service endpoint. This endpoint is created and the system will randomly allocate a port. If you do not want to configure it randomly, You can manually specify it. DatagramSocket ds = new DatagramSocket (9999); set the port to 9999, which is the sending port.

2. To encapsulate data in a packet package, you must specify the destination address and port. Byte [] buf = "hello, client". getBytes (); DatagramPacket dp = new DatagramPacket (buf, buf. length, InetAddress. getByName ("192.168.1.1"), 9999 );

3. Use the send method of the socket service to send the package. Ds. send (dp );

4. Disable the socket service. It is mainly to close resources. Ds. close ();

Acceptor:
1. Establish the udp socket service. Listen to a port. DatagramSocket ds = new DatagramSocket (9999 );
2. Define a buffer to encapsulate the buffer into a packet package. Byte [] buf = new byte [1024]; DatagramPacket dp = new DatagramPacket (buf, buf. length );
3. Store data into data packets through the socket receive method. Ds. receive (dp); The receive method produces a "blocking ".
4. Get the specified information in the package through the methods of data packet dp, such as getData (), getAddress (), and getPort.
5. Disable socket. Ds. close ();

Note: 1. When creating an initramsocket class instance, if the port is used, a SocketException exception will be thrown and the program is terminated illegally. capture this exception.

2. "blocking" is a specialized term that produces an internal loop that pauses the program in this place until a condition is triggered.

  • System implementation:

  • Code implementation:

Acceptor:

Public class Server {public static void main (String [] args) throws IOException {// bind the local IP address and specify the port number as 9999. datagramSocket server = new DatagramSocket (9999); // prepare a byte array, which can contain 1024 bytes and start receiving data. Byte [] bytes = new byte [1024]; // encapsulate the first 1024 bytes in the byte array into packet. DatagramPacket packet = new DatagramPacket (bytes, 1024); // store data in the data packet through the socket receive () method. Server. receive (packet); // print the data received by the server, at this time, the data has been parsed into the original data and is the actual received length String Msg = new String (packet. getData (), 0, packet. getLength (); System. out. println ("message received by the server" + Msg );}}

Sender:

Public class Client {public static void main (String [] args) throws IOException {// bind the local port number and randomly select a port number @ SuppressWarnings ("resource ") datagramSocket client = new DatagramSocket (); // send data to the Server String str = "Hello, I'm client"; // send byte [] bytes = str in bytes. getBytes (); // encapsulate byte information in packet to be sent. Note that the parameters to be obtained include all the bytes from 0 to the end of the byte array, the IP address and port number of the acceptor. Required rampacket packet = new DatagramPacket (bytes, 0, bytes. length, InetAddress. getByName ("127.0.0.1"), 9999); // send client. send (packet );}}

Output:

Note: you do not need to establish a connection between the CIDR Block and the receiving end during UDP communication. The send () and receive () methods are used to send and receive data, in addition, the sent and received data are carried by packet. During sending, the packet parameter should have the IP address of the receiver (through InetAddress. getByName () and port number.

 

 

If anything is wrong, please correct me. Thank you (● 'shanghai' ●)

 

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.