JAVA notes: Java Network Programming (4) UDP programming, network programming udp
All operations in the TCP protocol must establish a reliable connection, which consumes a lot of system resources. To reduce this overhead, another transmission protocol is provided in the network:
UDP protocol and unreliable connections are widely used in various chat tools.
In UDP development, mongorampacket is used to package the information to be sent, and then mongoramsocket is used to send the information.
UDP is mainly sent using the datagram protocol.
The main method of DatagramPacket is as follows:
It contains real information to be sent, which is called a datagram.
All the data packets are sent using DatagramSocket.
Instance:
Server:
Import java.net. datagramPacket; import java.net. datagramSocket; import java.net. inetAddress; public class UDPServer {public static void main (String args []) throws Exception {// All exceptions throw DatagramSocket ds = null; // define the object for sending the data packet: DatagramPacket dp = null; // declare the DatagramPacket object ds = new DatagramSocket (3000 ); // The server waits for the message sent by the server on port 3000 \ String str = "hello World !!! "; Dp = new DatagramPacket (str. getBytes (), str. length (), InetAddress. getByName ("localhost"), 9000); // use buf to save all information. out. println ("Send message. "); Ds. send (dp); // send the information out of ds. close ();}};
Client:
Import java.net. datagramPacket; import java.net. datagramSocket; public class UDPClient {public static void main (String args []) throws Exception {// All exceptions throw DatagramSocket ds = null; // define the object byte [] buf = new byte [1024] for receiving the datagram; // open up the space to receive the data; then rampacket dp = null; // declare the mongorampacket object ds = new mongoramsocket (9000); // The client waits for the server to send the message dp = new mongorampacket (buf, 9000) on port 1024 ); // use buf to save all the information. receive (dp); // String str = new String (dp. getData (), 0, dp. getLength () + "from" + dp. getAddress (). getHostAddress () + ":" + dp. getPort (); System. out. println (str); // output content }};