UDP programming
In the TCP index operation must establish a reliable connection, this will certainly waste a lot of system performance, in order to reduce this overhead, in the network also provides another transport protocol---UDP, unreliable connection, the protocol is widely used in various chat tools.
I use Datagrampacket in UDP development to wrap a message to be sent, and then use Datagramsocket to complete the sending of the information.
For example: Now chat with the chat tool function, then A's sent information B may not be acceptable, because the use of UDP protocol.
UDP is primarily sent using the datagram protocol.
Methods in the Datagrampacket
is a message that contains real information that is to be sent, called a datagram
All datagrams using Datagrampacket to send the operation
Datagramsocket
Then if you want to run the program, in the development of the datagram, you should first ensure that the client to open
ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;PublicClassudpclient{PublicStaticvoid Main (String args[])Throws exception{//All exceptions thrown Datagramsocket ds =null;//Define the object that receives the datagrambyte[] buf =NewBYTE[1024];//Opens up space to receive data datagrampacket DP =null; // declaration Datagrampacket Object ds = new datagramsocket (9000); // client waits for server to send information on port 9000 DP = new Datagrampacket (buf,1024); //// receive data string str = new String (Dp.getdata (), 0, Dp.getlength ()) + "from" + Dp.getaddress (). Gethostaddress () +": "+ Dp.getport (); System.out.println (str); // output
To further wait for the server to send information
ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;Importjava.net.InetAddress;PublicClassudpserver{PublicStaticvoid Main (String args[])Throws exception{//All exceptions thrown Datagramsocket ds =null; // Define the object that sent the datagram datagrampacket DP = null; // declaration Datagrampacket Object ds = new Datagramsocket (3000); // The server waits on port 3000 for the message String str = "Hello World!!!" new Datagrampacket (Str.getbytes (), Str.length (), Inetaddress.getbyname ("localhost"), 9000); //); Ds.send (DP); // send information out Ds.close ();};
UDP is an unreliable connection protocol, and the information sent by the server is not necessarily received by the client, but is sent by the datagram protocol.
Reprinted from Http://www.cnblogs.com/oumyye/p/4271198.html
Java Basics---Network programming (UDP programming)