In the TCP protocol, all operations must establish a reliable connection, the consumption of system resources is very large, in order to reduce this overhead, in the network provides another transport protocol:
UDP protocol, unreliable connection, is widely used in various chat tools.
In UDP development, use Datagrampacket to wrap a message to be sent, and then use Datagramsocket to complete the sending of the information.
UDP is primarily sent using the datagram protocol.
Datagrampacket Main methods:
Contains the actual information to be sent, called a datagram.
All datagrams are sent using Datagramsocket to complete the data.
Instance:
Server-side:
Import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress;p ublic class udpserver{ public static void Main (String args[]) throws exception{//all exceptions are thrown datagramsocket ds = NULL;//define the object that sent the datagram Datagrampacket DP = NULL;//declares Datagrampacket object ds = new Datagramsocket (3000);//server waits on port 3000 to send information on string str = "Hello world!!!";DP = new Datagrampacket (Str.getbytes (), Str.length (), Inetaddress.getbyname ("localhost"), 9000); All information is saved using BUF System.out.println ("Send message. ");d S.send (DP);//Send information out ds.close ();}};
Client:
Import java.net.DatagramPacket; import java.net.DatagramSocket;p ublic class udpclient{public static void Main (String Args[]) throws exception{//all exceptions throw datagramsocket ds = NULL;//define object to receive datagram byte[] buf = new byte[1024];//Open space to receive data Datagra Mpacket DP = NULL;//declares Datagrampacket object ds = new Datagramsocket (9000);//client waits on port 9000 for server to send information DP = new Datagrampacket (buf, 1024); All information is saved using BUF ds.receive (DP) ;//Receive data string str = new String (Dp.getdata (), 0,dp.getlength ()) + "from" + dp.getaddres S (). Gethostaddress () + ":" + dp.getport (); System.out.println (str);//output content}};
Java NOTES: Java Network programming (IV) UDP programming