Java Network Programming-UDP
Client code first
Package com.test.net; import java.net. datagramPacket; import java.net. datagramSocket; import java.net. inetAddress; public class UDPClient {/*** UDP client */public static void main (String [] args) throws Exception {DatagramSocket socket = new DatagramSocket (); string str = "hello"; byte [] buf = str. getBytes (); DatagramPacket packet = new DatagramPacket (buf, buf. length, InetAddress. getByName ("127.0.0.1"), 1111);/* send packets directly */socket. send (packet );}}
Server code
Package com.test.net; import java.net. datagramPacket; import java.net. datagramSocket; import java.net. inetAddress; import java.net. socketException; public class UDPServer {/*** UDP server */public static void main (String [] args) throws Exception {DatagramSocket socket = new DatagramSocket (1111 ); byte [] buf = new byte [256]; DatagramPacket packet = new DatagramPacket (buf, buf. length);/* listener, blocking */socket. receive (packet); String received = new String (packet. getData (); System. out. println (received );}}
First, let's talk about UDP. UDP is a non-connection protocol. Simply put, it is a one-way transmission. You do not need to establish a connection in advance, nor need to return packets. Therefore, you only need an IP address and port, and UDP can send packets to this port. If there is any such IP address or port, or the other party does not receive the packets, UDP will not work. Therefore, the most important thing in UDP is the two classes. One is mongoramsocket and the other is mongorampacket. The first class is similar to socket, and the second class is UDP packet.
On the server, the receive method of mongorampacket is blocked, which is equivalent to listening until the datagram is listened.
Output result
The result is that the server outputs hello.