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