Java Learning Note 52 (Network programming: UDP protocol Case)

Source: Internet
Author: User

InetAddress class:

Represents an IP address in the Internet, example:

 Packagedemo;Importjava.net.InetAddress;Importjava.net.UnknownHostException; Public classInetaddressdemo { Public Static voidMain (string[] args)throwsunknownhostexception {function1 ();    Function2 (); }     Public Static voidFunction1 ()throwsunknownhostexception {inetaddress inet=Inetaddress.getlocalhost (); System.out.println (Inet.gethostname ());//Get host name//Output: Desktop-q3o8aeoSystem.out.println (Inet.gethostaddress ());//Get host IP//Output: 192.168.87.1    }     Public Static voidFunction2 ()throwsunknownhostexception {//Get additional IPInetAddress inet = Inetaddress.getbyname ("www.baidu.com");        System.out.println (inet); //Output: www.baidu.com/111.13.100.92    }}
View Code

UDP protocol: No connection communication protocol, maximum 64KB, unsafe

TCP protocol: Connection-oriented communication protocol, reliable and secure, three-time handshake to confirm the connection, relatively slow, suitable for large data transmission

UDP Example:

Send side:

 Packagedemo;Importjava.io.IOException;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;Importjava.net.InetAddress; Public classUdpsend { Public Static voidMain (string[] args) {Try {            byte[] data = "Hello". GetBytes (); InetAddress inet= Inetaddress.getbyname ("127.0.0.1"); Datagrampacket DP=NewDatagrampacket (data, Data.length, inet, 6000); Datagramsocket DS=NewDatagramsocket ();            Ds.send (DP);        Ds.close (); } Catch(IOException ex) {System.out.println (ex); }    }}
View Code

Receiving end:

 Packagedemo;Importjava.io.IOException;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket; Public classudpreceive { Public Static voidMain (string[] args) {Try{datagramsocket ds=NewDatagramsocket (6000); byte[] data =New byte[1024]; Datagrampacket DP=Newdatagrampacket (data, data.length);            Ds.receive (DP); intLength =dp.getlength (); String IP=dp.getaddress (). gethostaddress (); SYSTEM.OUT.PRINTLN (IP+ ":" +NewString (data, 0, length));        Ds.close (); } Catch(IOException ex) {System.out.println (ex); }    }}
View Code

Run the receive end first, then run the send side, the result:

Output: 127.0.0.1: Hello

Functions can be improved to achieve keyboard input chat:

Send side:

 Packagedemo;Importjava.io.IOException;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;Importjava.net.InetAddress;ImportJava.util.Scanner; Public classUdpsend { Public Static voidMain (string[] args) {Try{Scanner sc=NewScanner (system.in); Datagramsocket DS=NewDatagramsocket (); InetAddress inet= Inetaddress.getbyname ("127.0.0.1");  while(true) {String message=Sc.nextline (); byte[] data =message.getbytes (); Datagrampacket DP=NewDatagrampacket (data, Data.length, inet, 7000);            Ds.send (DP); }        } Catch(IOException ex) {System.out.println (ex); }    }}
View Code

Receiving end:

 Packagedemo;Importjava.io.IOException;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket; Public classudpreceive { Public Static voidMain (string[] args) {Try{datagramsocket ds=NewDatagramsocket (7000); byte[] data =New byte[1024];  while(true) {Datagrampacket DP=Newdatagrampacket (data, data.length);                Ds.receive (DP); intLength =dp.getlength (); String IP=dp.getaddress (). gethostaddress (); SYSTEM.OUT.PRINTLN (IP+ ":" +NewString (data, 0, length)); }        } Catch(IOException ex) {System.out.println (ex); }    }}
View Code

Successively run, the message sent at the sender can be received at any time at the receiving end, here to achieve a simple chat function

You can also chat between multiple computers under the same LAN, as long as the corresponding IP address is changed

Java Learning Note 52 (Network programming: UDP protocol Case)

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.