Java basic Knowledge Review Java Socket Learning (a)--UDP protocol programming

Source: Internet
Author: User

UDP Transport: For a non-connected protocol, unreliable, just send the application to the IP layer of the datagram packet sent out, there is no guarantee to send out the datagram packets can reach the destination. No longer the client and the server to establish a connection, there is no time-out retransmission mechanism, fast transmission is its advantages. It is like sending a letter and putting it in a mailbox bucket, neither ensuring that the letter is lost in the mail, nor that the letter is sent to the destination sequentially.

Look at the Java API for Java.net.DatagramSocket and java.net. Datagrampacket class:

datagramsocket: This class represents the socket (IP address and port number) used to send and receive datagram packets.

Datagrampacket : packet Delivery service for non-connected packets. Each message is routed from one machine to another based only on the information contained in the package. Multiple packages sent from one machine to another may choose different routes, or they may arrive in a different order. No warranties are made for package delivery.

Let's look at a simple receiver and server-side code:

Receive-Side code:

Importjava.io.IOException;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket; Public classUdprecedemo {/**     * @paramargs *@throwsIOException*/     Public Static voidMain (string[] args)throwsIOException {System.out.println ("Receive-Side start ..."); /** The idea of setting up a UDP receiving end.         * 1, to set up a UDP socket service, because it is to receive data, you must specify a port number. * 2, create a packet to store the received data.         It is convenient to parse the data with the method of the Packet object.         * 3, use the Receive method of the socket service to store the received data in a packet.         * 4. The data in the packet is parsed by means of a packet. * 5, Close resources*/                //1, set up the UDP socket service. Datagramsocket ds =NewDatagramsocket (10000);//Port number of the receiving application//2, create a packet to receive the length of the packet        byte[] buf =New byte[1024]; Datagrampacket DP=NewDatagrampacket (buf,buf.length); //3, use the Receive method to store the data in a packet. Ds.receive (DP);//a blocking type. //4, through the method of the packet object, parse the data, for example, address, port, data content. String IP =dp.getaddress (). gethostaddress (); intPort = Dp.getport ();//returns the port number of the hostString Text =NewString (Dp.getdata (), 0, Dp.getlength ()); SYSTEM.OUT.PRINTLN (IP+ ":" +port+ ":" +text); //5, close the resource. Ds.close (); }}

Send-side code:

Importjava.io.IOException;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;Importjava.net.InetAddress; Public classUdpsenddemo {/**     * @paramargs *@throwsIOException*/     Public Static voidMain (string[] args)throwsIOException {System.out.println ("Send side start ..."); /** Create the Send side of the UDP transport.         * Idea: * 1, set up a UDP socket service.          * 2, the data to be sent is encapsulated in the datagram packet.         * 3, send data packets via UDP socket service.         * 4, close the socket service. */        //1,udpsocket Services. Use the Datagramsocket object. Datagramsocket ds =NewDatagramsocket (); //2, the data to be sent is encapsulated in the packet. String str = "UDP transmission ....." "; //use Datagrampacket to encapsulate the data into the package.         byte[] buf =str.getbytes (); //Datagrampacket contains information indicating the data to be sent, its length, the IP address of the remote host, and the port number of the remote host. Datagrampacket DP =NewDatagrampacket (Buf,buf.length,inetaddress.getbyname ("QT-201216220606"), 10000); //3. Send the datagram via the UP socket service. Use the Send method. Ds.send (DP); //4, close the resource. Ds.close (); }}

The receiving side starts, then the sending side starts, the result sends to the receiving side host sends: 192.168.0.101:4882:UDP transmission ... Content.

Other unchanged, the sender of the code changes, into the keyboard can be implemented input (UDP protocol):

 Packagecn.itcast.net.p2.udp;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;Importjava.net.InetAddress; Public classUDPSendDemo2 {/**     * @paramargs *@throwsIOException*/     Public Static voidMain (string[] args)throwsIOException {System.out.println ("Send side start ..."); /** Create the Send side of the UDP transport.         * Idea: * 1, set up a UDP socket service.          * 2, the data to be sent is encapsulated in the packet.         * 3, send data packets via UDP socket service.         * 4, close the socket service. */        //1,udpsocket Services. Use the Datagramsocket object. Datagramsocket ds =NewDatagramsocket (); //The contents of the keyboard input are sent to the client, using bytes to convert the stream to character       BufferedReader bufr = new BufferedReader (new InputStreamReader (system.in));        String line = null;            while ((Line=bufr.readline ())!=null) {byte[] buf = Line.getbytes ();            Datagrampacket DP = new Datagrampacket (Buf,buf.length,inetaddress.getbyname ("192.168.0.101"), 10000);                        Ds.send (DP); if ("Over". Equals (line)) break; }                //4, close the resource. Ds.close (); }}

Start the receiving end, start the server, input on the server, receive the message on the receiving side ....

Simple multi-person chat room implementation: Using multi-threading, IO:

Receiving end:

ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket; Public classReceImplementsRunnable {PrivateDatagramsocket ds;  Publicrece (datagramsocket ds) { This, D1 =ds; } @Override Public voidrun () {Try {             while(true) {                //2. Create a packet.                 byte[] buf =New byte[1024]; Datagrampacket DP=NewDatagrampacket (buf, buf.length); //3, use the Receive method to store the data in a packet. Ds.receive (DP);//a blocking type. //4, through the method of the packet object, parse the data, for example, address, port, data content. String IP =dp.getaddress (). gethostaddress (); intPort =Dp.getport (); String text=NewString (Dp.getdata (), 0, Dp.getlength ()); SYSTEM.OUT.PRINTLN (IP+ "::" +text); if(Text.equals ("Over") {System.out.println (IP+".... Exit chat Room "); }            }        } Catch(Exception e) {} }}

Service side:

 PackageCn.itcast.net.p3.chat;ImportJava.io.BufferedReader;ImportJava.io.InputStreamReader;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;Importjava.net.InetAddress; Public classSendImplementsRunnable {PrivateDatagramsocket ds;  PublicSend (datagramsocket ds) { This, D1 =ds; } @Override Public voidrun () {Try{BufferedReader Bufr=NewBufferedReader (NewInputStreamReader (system.in)); String Line=NULL;  while((Line=bufr.readline ())! =NULL){                                                byte[] buf =line.getbytes (); //indicates that the message is sent to all IP addresses of 192.168.0, sending a broadcast IP address the last 1-254 of all hosts will receiveDatagrampacket DP =NewDatagrampacket (Buf,buf.length,inetaddress.getbyname ("192.168.0.255"), 10001);                                Ds.send (DP); if("886". Equals (line)) Break;        } ds.close (); } Catch(Exception e) {}} }

Start the program:

Importjava.io.IOException;ImportJava.net.DatagramSocket; Public classChatdemo {/**     * @paramargs *@throwsIOException*/     Public Static voidMain (string[] args)throwsIOException {datagramsocket send=NewDatagramsocket (); Datagramsocket rece=NewDatagramsocket (10001); NewThread (Newsend). Start (); NewThread (Newrece (rece)). Start (); }}

Java basic Knowledge Review Java Socket Learning (a)--UDP protocol programming

Related Article

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.