Connection Address: http://www.cnblogs.com/mengdd/archive/2013/03/10/2952673.html
Communicating with a non-connected datagram (UDP) what is datagram?
The datagram is an independent packet transmitted on the Internet, whether the datagram can reach the destination correctly, the time of arrival, the order and the correctness of the content are not guaranteed.
Datagram and datagrampacket classes are used in Java.
The Datagramsocket class uses the UDP protocol to implement a client-server socket.
Send () sends datagrams.
Receive () Receives datagrams.
You can use the example of letter letters to compare UDP communication.
At this point datagrampacket is the equivalent of a letter wrapped in an envelope. After filling in the address and the recipient, you can send it out.
A simple example of UDP communication
Package Com.example.network;import Java.net.datagrampacket;import Java.net.datagramsocket;import Java.net.inetaddress;public class udpunit1{public static void Main (string[] args) throws Exception { Datagramsocket datagramsocket = new Datagramsocket (); Constructs a datagram packet String str = "Hello world"; Used public Datagrampacket (byte buf[], int length,inetaddress address, //int port) in the form datagrampacket packet = new Datagrampacket (Str.getbytes (), str.length (), Inetaddress.getbyname ("localhost"), 7000); Send packet datagramsocket.send (packet); Receive packet byte[] buffer = new byte[1024]; Datagrampacket Packet2 = new Datagrampacket (buffer, +); Datagramsocket.receive (Packet2); Output received data System.out.println (new String (buffer, 0, packet2.getlength ())); Datagramsocket.close (); }}
Package Com.example.network;import Java.net.datagrampacket;import Java.net.datagramsocket;public class UdpUnit2{ Public static void Main (string[] args) throws Exception { Datagramsocket socket = new Datagramsocket (7000); Receive information byte[] buffer = new byte[1024]; Datagrampacket packet = new Datagrampacket (buffer, 1024x768); Receiving socket.receive (packet); Output System.out.println (new String (buffer, 0, packet.getlength ())); Returns the message String str = "welcome! "; Datagrampacket Packet2 = new Datagrampacket (Str.getbytes (), str.length (), packet.getaddress (), Packet.getport () );//fill in the sender's information here socket.send (Packet2); Socket.close (); }}
The runtime first runs UdpUnit2 because it is waiting to be received at the beginning, and then runs UdpUnit1, which sends the message "Hello World" to UdpUnit2, UdpUnit2 receives the message and returns "welcome! ”。
One of the strangest places is that the exclamation mark after the welcome is displayed after the UdpUnit1 is received and output.
The reason is unknown, (is this the evidence that the UDP transmission data is unreliable?) Looking for talent pointing.
Resources
Santhiya Garden Zhang Long teacher Java SE Series video tutorial.
Java Network Programming (vi) communication using a non-connected datagram (UDP)