Java Learning Notes UDP protocol

Source: Internet
Author: User

All TCP operations are based on reliable links

UDP (Datagram Protocol) messages sent by the other party do not necessarily receive, all the information is sent in the form of a datagram

Using the Datagramsocket class and the Datagrampacket class to complete the operation

Server-side UDP:

Importjava.net.*;ImportJava.io.*;//defining server-side receive information Public classTestudpserver { Public Static voidMain (string[] args) {Try{datagramsocket ds=NewDatagramsocket (9000);//Setting the listening port number            byteBytes[] =New byte[1024];//1KBDatagrampacket DP =NewDatagrampacket (bytes,bytes.length);//Datagrampacket (byte[] buf, int length) construction method//Set loop ReceiveString str =NULL;  while(true) {ds.receive (DP);//blocking method, until the data is received to unlockSYSTEM.OUT.PRINTLN ("Receive data:"); STR=NewString (Bytes,0,dp.getlength ());//Note After receive, the DP is populated with the bytes arraySYSTEM.OUT.PRINTLN (str + ":" + dp.getaddress (). GetHostName () + "-----" +dp.getsocketaddress ()); }        }Catch(socketexception E1) {e1.printstacktrace (); }Catch(IOException E2) {e2.printstacktrace (); }    }    }

Client UDP:

Importjava.net.*;ImportJava.io.*;//Define client Send information Public classtestudpclient { Public Static voidMain (string[] args) {Try{datagramsocket ds=NewDatagramsocket (8888);//Setting the Listening portString str = "Hello word!"; byteBytes[] =str.getbytes (); //Datagrampacket (byte[] buf, int offset, int length, socketaddress address)//inetsocketaddress (inetaddress addr, int port)Datagrampacket DP =NewDatagrampacket (Bytes,0,bytes.length,NewInetsocketaddress ("192.168.0.121", 9000));            Ds.send (DP);        Ds.close (); }Catch(SocketException e) {e.printstacktrace (); }Catch(IOException E2) {e2.printstacktrace (); }    }    }

Results:

Java Learning Notes UDP protocol

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.