Refer to Chuan Zhi podcast Bi Xiangdong JAVA video. Note: The address must be specified for each packet sent by mongoramsocket, while the Socket specifies the address when it is created for the first time. All data will be sent through this socket in the future. A socket is an endpoint for communication between two machines. socket means A socket, so it can be understood that each of the two parties has A socket, which is used for communication. Sender:
Package com. lstrap. corejava; import java.net. datagramSocket; import java.net. inetAddress; import java.net. extends rampacket; public class UDPSendTest {public static void main (String [] args) throws Exception {// 1. Create a DatagramSocket for UDP data transmission. DatagramSocket socket = new DatagramSocket (); // 2. Create the data packet byte [] buf = "Hello World. ". getBytes (); DatagramPacket packet = new DatagramPacket (buf, buf. length, InetAddress. getByName ("192.168.136.222"), 7879); // 3. Send the socket. send (packet); // 4. Close the socket connection. close ();}}
Acceptor:
Package com. lstrap. corejava; import java.net. datagramSocket; import java.net. datagramPacket; import java.net. inetAddress; public class UDPReceiveTest {public static void main (String [] args) throws Exception {// 1. Create a DatagramSocket; DatagramSocket socket = new DatagramSocket (7879 ); // 2. Create a data packet for receiving content. Byte [] buf = new byte [1024]; DatagramPacket packet = new DatagramPacket (buf, buf. length); // 3. receive data socket. receive (packet); System. out. println (packet. getAddress (). getHostAddress () + ":" + packet. getPort (); // System. out. println (packet. getData (). toString (); // The print information of the preceding statement is incorrect. Because getData () returns byte [] data, toString will serialize it instead of extract characters. Use the following methods: System. out. println (new String (packet. getData (), 0, packet. getLength (); // 4. Close the connection. Socket. close ();}}