Java basics-network programming (UDP programming) and basic udp
UDP Programming
TCP index operations must establish reliable connections, which will definitely waste a lot of system performance. To reduce this overhead, another transmission protocol-UDP, unreliable connection, is provided in the network. This protocol is 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.
For example, if you use the chat tool to chat, the information sent by A is not necessarily acceptable because UDP protocol is used.
UDP is mainly sent using the datagram protocol.
Methods In DatagramPacket
It contains real information to be sent, called a Datagram
All data packets are sent using mongorampacket.
DatagramSocket
If you want to run the program, you must first ensure that the client is enabled in the development of the datagram.
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 }};
Wait for the server to send messages
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 ();}};
UDP is an unreliable connection protocol. The client may not receive the information sent by the server. It uses the datagram protocol for sending.