Java Network Programming (3)--UDP

Source: Internet
Author: User

UDP is mainly used in Java Datagramsocket to achieve communication, data is generally encapsulated through datagrampacket;

The sender only needs to specify the address and port of the receiver, and then through the Send () method can be encapsulated in the Datagrampacket data sent past!

The receiver only needs to use the same datagramsocket and a datagrampacket to receive the data, accept just specify the port to accept, as follows:

Sender:

  

 Packagecom.seven.exercise1;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;Importjava.net.InetAddress; Public classUdpsend { Public Static voidMain (string[] args)throwsException {//1.UDP ServiceDatagramsocket ds =NewDatagramsocket (); //2. Encapsulating data to Datagrampacket        byte[] data = "Hello UDP socket". GetBytes (); InetAddress inetaddress= Inetaddress.getbyname ("127.0.0.1");//address.Datagrampacket Datagrampacket =NewDatagrampacket (data, Data.length, InetAddress, 10000); //3. Send Datads.send (Datagrampacket); //4. CloseDs.close (); }}

The receiving party;

 Packagecom.seven.exercise1;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket; Public classudpreceive { Public Static voidMain (string[] args)throwsexception{//1. Create a new receiving partyDatagramsocket Datagramsocket =NewDatagramsocket (10000); //2. Bind to receive package        byte[] B =New byte[1024]; Datagrampacket DP=NewDatagrampacket (b,b.length); //3. Receiving DataDatagramsocket.receive (DP); //4. If you receive the data, print it out.String data =NewString (Dp.getdata (), 0, Dp.getlength ()); System.out.println (Dp.getaddress (). Gethostaddress ()+ "----->" +data); //5. Close;Datagramsocket.close (); }}

Because UDP is non-connected, so no matter how to run can, but in order to be able to accept the data, we have to run the receiver first, then to run the sender, so as to see the effect, otherwise the packet loss will not see what the effect of = =.

Java Network Programming (3)--UDP

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.