Java UDP network programming

Source: Internet
Author: User

Importjava.net.*;/*sending text data over a UDP transmission 1. Setting up the Socket Service 2. Provide data and encapsulate it in a packet 3. Send data packets through the Sokect service delivery function 4. Close Resources*/classudpsend{ Public Static voidMain (string[] arg)throwsException {//1. Create a UDP service. by Datagramsocket ObjectDatagramsocket ds =NewDatagramsocket (1234); //2. Identify the data and encapsulate it as a packet        byte[] buf = "UDP is Coming". GetBytes (); Datagrampacket DP=NewDatagrampacket (Buf,buf.length,inetaddress.getbyname ("127.0.0.1"), 4567); //3. Send the existing data packets through the socket serviceDs.send (DP); //4. Close ResourcesDs.close (); }    }/*Requirements: Define an application to be willing to receive UDP protocol transmission data ideas: 1. Define a Udpsocket service, typically listening on a port 2. Define a packet. Because you want to store the received byte data because there are more features in the packet object that can extract different data information from the byte Data 3. The received data is stored in a defined packet by the socket service's Receive method 4. With the unique functionality of the packet object, these different data are taken out and printed on the console 5. Close Resources */classudprece{ Public Static voidMain (string[] args)throwsexception{//1. Create UDP, set up endpointDatagramsocket ds=NewDatagramsocket (4567); //2. Define the packet to store        byte[] buf=New byte[1024]; Datagrampacket DP=NewDatagrampacket (buf,buf.length); //3. Data that is received indirectly through the receive method is stored in the packetDs.receive (DP); //4. Get the data from the data packet methodString ip=dp.getaddress (). gethostaddress (); String Data=NewString (Dp.getdata (), 0, Dp.getlength ()); intport=Dp.getport (); SYSTEM.OUT.PRINTLN (IP+ ":" +port+ "------" +data); //5. Close ResourcesDs.close (); }    }

Java UDP network programming

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.