What is DatagramSocket (UDP) in Java?

DatagramSocket in Java is a class that enables communication using the User Datagram Protocol (UDP). It allows for the sending and receiving of packets, or datagrams, over a network without establishing a connection. This method of communication is typically used in scenarios where speed is more critical than reliability, such as video streaming or online gaming.

DatagramSockets operate by providing a simple interface to send and receive packets, making it an essential tool for network programming in Java. Each datagram sent contains its own destination address and port number, allowing for direct communication with other services.

Below is a simple example of using a DatagramSocket to send and receive messages:

// Sender import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; public class UDPSender { public static void main(String[] args) throws Exception { DatagramSocket socket = new DatagramSocket(); String message = "Hello, World!"; byte[] buffer = message.getBytes(); InetAddress address = InetAddress.getByName("localhost"); DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, 9876); socket.send(packet); socket.close(); } } // Receiver import java.net.DatagramPacket; import java.net.DatagramSocket; public class UDPReceiver { public static void main(String[] args) throws Exception { DatagramSocket socket = new DatagramSocket(9876); byte[] buffer = new byte[1024]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); socket.receive(packet); String receivedMessage = new String(packet.getData(), 0, packet.getLength()); System.out.println("Received: " + receivedMessage); socket.close(); } }

DatagramSocket UDP Java networking DatagramPacket network programming