Android (Java) Learning Note 80:UDP protocol sending data

Source: Internet
Author: User

  UDP protocol sends data: we always run the receiving end first, then run the Send side
Send side:

1
Packagecn.itcast_02;2 3 Importjava.io.IOException;4 ImportJava.net.DatagramPacket;5 ImportJava.net.DatagramSocket;6 Importjava.net.InetAddress;7 /*8 * UDP protocol sends data:9 * A: Create A send-side socket object Ten * B: Create the data and package the data One * C: Call the Send method of the socket object to send the packet A * D: Releasing Resources - */ - Public classSenddemo { the Public Static voidMain (string[] args)throwsIOException { - //Create send-side socket object - //Datagramsocket () -Datagramsocket ds =NewDatagramsocket (); + - //Create data and package the data + //Datagrampacket (byte[] buf, int length, inetaddress address, int port) A //Create Data at byte[] bys = "HELLO,UDP, here I Come". GetBytes (); //transcoding - //Length - intLength =bys.length; - //IP Address object -InetAddress address = Inetaddress.getbyname ("192.168.12.92"); - //Port in intPort = 10086; -Datagrampacket DP =Newdatagrampacket (bys, length, address, port); to + //Call the Send method of the socket object to send the packet - //public void Send (Datagrampacket p) the Ds.send (DP); * $ //Release ResourcesPanax Notoginseng ds.close (); - } the}

  receiving end:
1
Packagecn.itcast_02;2 3 Importjava.io.IOException;4 ImportJava.net.DatagramPacket;5 ImportJava.net.DatagramSocket;6 Importjava.net.InetAddress;7 8 /*9 * UDP protocol Receive data: Ten * A: Create a receiver socket object one at a * B: Create a packet (Receive container) * C: Call the Socket object's receive method to receive data in the system * D: Parse the packet and display it in the console * E: Release the Resource the */ - Public classReceivedemo { - Public Static voidMain (string[] args)throwsIOException {18//Create receive End Socket object//datagramsocket (int port) -Datagramsocket ds =NewDatagramsocket (10086); + 22//Create a packet (Receive container)//Datagrampacket (byte[] buf, int length) - byte[] Bys =New byte[1024]; - intLength =bys.length; -Datagrampacket DP =Newdatagrampacket (bys, length); - 28//Call the Receive method of the socket object receive data in//public void receive (Datagrampacket p) -Ds.receive (DP);//block type to 32//parse the packet and display it in console 33//Get the IP of the other side the //Public inetaddress getaddress () *InetAddress address =dp.getaddress (); $String IP =address.gethostaddress ();Panax Notoginseng //Public byte[] GetData (): Get Data buffer - //public int GetLength (): Gets the actual length of the data the byte[] Bys2 =Dp.getdata (); + intLen =dp.getlength (); AString s =NewString (BYS2, 0, Len); theThe data passed by SYSTEM.OUT.PRINTLN (IP +) is: "+s); + 44//Release Resources $ ds.close (); $ } -}

Here Ds.close ():

The memory recovery mechanism of J Ava is also a life cycle when resources reach a certain limit before they start to recycle. Use Close () to recover resources in a timely manner and be more efficient. Use Close () to release resources in a timely manner, without having to wait until the last resource is exhausted to begin the painful recycling process, and from good programming habits, you should consider freeing up memory resources when you're done. To develop a good programming habit.

First of all, we are running the receiving end, because if you do not first run the receiving end, first run the sending side, the data will not receive. But at the same time, if the receiver is run first, but no data is received, it is impossible to parse the data and display the data, so: first run the receiving end, then run the sending side, and we also define the receiving end as blocking, (that is, waiting for data to send over).

UDP sends data and receives data plots:

Optimization of UDP sending data and receiving data code:

UDP protocol sends data: we always run the receiving end first, then run the Send side
Send side:

1
Packagecn.itcast_03;2 3 Importjava.io.IOException;4 ImportJava.net.DatagramPacket;5 ImportJava.net.DatagramSocket;6 Importjava.net.InetAddress;7 8 Public classSenddemo {9 Public Static voidMain (string[] args)throwsIOException {Ten //Create a Socket object on the send side OneDatagramsocket ds =NewDatagramsocket (); A - //Create data and package - byte[] bys = "HelloWorld". GetBytes (); theDatagrampacket DP =NewDatagrampacket (bys, Bys.length, -Inetaddress.getbyname ("192.168.12.92"), 12345); - - //Send data + Ds.send (DP); - + //Release Resources A ds.close (); at } -}

Receiving end:

1
Packagecn.itcast_03;2 3 Importjava.io.IOException;4 ImportJava.net.DatagramPacket;5 ImportJava.net.DatagramSocket;6 7/* 8 * Multiple start receive end: 9 * java.net.BindException:Address already in Use:cannot BIND10 * port is occupied. one by one * A Public classReceivedemo { - Public Static voidMain (string[] args)throwsIOException { - //Create a Socket object on the receiving end theDatagramsocket ds =NewDatagramsocket (12345); - - //Create a package - byte[] Bys =New byte[1024]; +Datagrampacket DP =NewDatagrampacket (bys, bys.length); - + //Receive Data A Ds.receive (DP); at - //Parse Data -String IP =dp.getaddress (). gethostaddress (); -String s =NewString (Dp.getdata (), 0, Dp.getlength ()); -System.out.println ("from" + IP + "data is:" +s); - in //Release Resources - ds.close (); to } +}

Android (Java) Learning Note 80:UDP protocol sending data

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.