UDP Simple Example

Source: Internet
Author: User

Receiver: 1, establish the Udpsocket service, set the port to the receiver; 2. Define an empty packet to store the received byte data, and use the packet object to easily extract the different data information in the byte data; 3. The received data is stored in a defined packet through the Receive method of the socket service, and the data is removed by the unique functions of the packet object, printed on the console; 5. Close the resource.
classudprecevie{ Public Static voidMain (string[] args)throwsException {datagramsocket ds=NewDatagramsocket (10000);  while(true)        {             byte[] buf =New byte[1024]; Datagrampacket DP=NewDatagrampacket (But, but.length); Ds.receive (DP);//blocking method, no data, etc.String IP =dp.getaddress (). gethostadress (); String Data=NewString (Dp.getdata (), 0, Dp.getlength ()); intPort =Dp.getport ();    } ds.close (); }}

Send receive with Datagramsocket, receive (Datagrampacket p), send (Datagrampacket p), Datagrampacket for encapsulating data. Send end: 1, establish Udpsocket service, 2, provide data, and encapsulate data into packet, 3, send data packets by socket service, 4, close resource.
class udpsend{    publicstaticvoidthrows  Exception    {         New Datagramsocket ();         byte [] data = "UDP come in". GetBytes ();         New Datagrampacket (data, Data.length, Inetaddresss.getbyname ("192.168.1.255"), +);        Ds.send (DP);        Ds.close ();    }}

UDP Simple Example

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.