Java UDP Protocol Transport

Source: Internet
Author: User

Using the UDP protocol to write a network program, set the receiver Terminal program listening port is 8001, the sender sends the data is "Hello, World".

Receiving end:

1 Importjava.net.*;2  Public classExample {3 4      Public Static voidMain (string[] args)throwsException5         {6             byte[] buf=New byte[1024];7Datagramsocket ds=NewDatagramsocket (8001);8Datagrampacket dp=NewDatagrampacket (buf,1024);9System.out.println ("Waiting to receive data");Ten Ds.receive (DP); OneString str=NewString (Dp.getdata ()); A System.out.println (str);  - ds.close (); -         } the  -}

Send side:

1 Importjava.net.*; 2  Public classexample1 {3   4      Public Static voidMain (string[] args)throwsexception{5Datagramsocket ds=NewDatagramsocket (3000); 6String str= "Hello, World"; 7Datagrampacket dp=NewDatagrampacket (Str.getbytes (), Str.length (), Inetaddress.getbyname ("localhost"), 8001);8SYSTEM.OUT.PRINTLN ("Send Message"); 9 Ds.send (DP); Ten Ds.close ();  One     }   A}

Operation Result:

Java UDP Protocol Transport

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.