Java bit-by-bit UDP-manipulating classes: DatagramSocket and DatagramPacket

Source: Internet
Author: User
Tags time in milliseconds

1. Basic concepts:

A. zoorampacket and initramsocket are located in the java.net package.

B. DatagramPacket indicates the data datagram that stores the data, and DatagramSocket indicates the socket that accepts or sends the data datagram.

C. The network link composed of all these two types is based on the UDP protocol and is an unreliable protocol.

2. Basic usage of DatagramSocket

DatagramSocket class: Creates a Socket instance for receiving and sending UDP packets.
DatagramSocket (): creates an instance. It 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 regularly monitors the Port packets.
DatagramSocket (int port, InetAddress localAddr): This is a very useful builder. When a machine has more than one IP address, the instance it creates only receives packets from LocalAddr, the packets received by the specified IP address.

Receive (DatagramPacket d): receives data packets to d. The receive method generates a "blocking ".
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.

Note: When creating an initramsocket instance, if the port has been used, a SocketException will be generated and thrown, leading to illegal program termination. capture this exception.

2. Basic usage of DatagramPacket

DatagramPacket: used to process packets. It packs data such as the byte array, target address, and target port into packets or disassembles the packets into byte arrays.
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): 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.
GetData (): it obtains the byte array encoding of packets from the instance.

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.


3. In the sample code, package the data packet after receiving the keyboard input.
Public class UdpClient {// defines the destination public static final int DEST_PORT = 30000; public static final String DEST_IP = "127.0.0.1 "; // define the maximum size of each datagram as 4 kb private static final int DATA_LEN = 4096; // define the byte array byte [] inBuff = new byte [DATA_LEN] for receiving network data; // create the jsonrampacket object private jsonrampacket inPacket = new jsonrampacket (inBuff, inBuff. length); // define a jsonrampacket object for sending private jsonrampacket outPacket = null; public void init () throws IOException {try (// create a client initramsocket, use random port DatagramSocket socket = new DatagramSocket () {// initialize the sender ramsocket for sending. It contains a byte array outPacket = new DatagramPacket (new byte [0], 0, InetAddress. getByName (DEST_IP), DEST_PORT); // create the keyboard input stream Scanner scan = new keyboard (System. in); // read the keyboard input while (scan. hasNextLine () {// converts a line of string input by the keyboard into a byte array byte [] buff = scan. nextLine (). getBytes (); // set the byte data outPacket in the DatagramPacket used for sending. setData (buff); // sends the datagram socket. send (outPacket); // read the data in the Socket and put the data in the byte array encapsulated by inPacket. receive (inPacket); System. out. println (new String (inBuff, 0, inPacket. getLength () ;}} public static void main (String [] args) throws IOException {new UdpClient (). init ();}}

The receiver receives UDP packets.
Public class UdpServer {public static final int PORT = 30000; // defines the maximum size of each datagram as 4 kb private static final int DATA_LEN = 4096; // define the byte array for receiving Network Data byte [] inBuff = new byte [DATA_LEN]; // create the jsonrampacket object private jsonrampacket inPacket = new jsonrampacket (inBuff, inBuff. length); // define a private DatagramPacket object used for sending; // define a string array, string [] books = new String [] {"Crazy Java handout", "lightweight Java EE Enterprise Application Practice", "crazy Android handout ", "Crazy Ajax handout"}; public void init () throws IOException {try (// create the initramsocket object initramsocket socket = new initramsocket (PORT )) {// receives data cyclically for (int I = 0; I <1000; I ++) {// reads data in the Socket, the read data is put into the inPacket encapsulated array socket. receive (inPacket); // judge inPacket. whether getData () and inBuff are the same Array System. out. println (inBuff = inPacket. getData (); // convert the received content into a string and output the System. out. println (new String (inBuff, 0, inPacket. getLength (); // retrieves an element from the string array as the sending Data byte [] sendData = books [I % 4]. getBytes (); // use the specified byte array as the sending data, and use the received mongorampacket's // source SocketAddress as the target SocketAddress to create mongorampacket outPacket = new mongorampacket (sendData, sendData. length, inPacket. getSocketAddress (); // send data socket. send (outPacket) ;}} public static void main (String [] args) throws IOException {new UdpServer (). init ();}}






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.