Java DatagramSocket Class
Java includes the DatagramSocket class to handle UDP (User Datagram Protocol) communication processes. UDP operates without establishing connections and offers faster transmission by not ensuring message delivery unlike TCP.

The DatagramSocket serves as the tool for sending DatagramPacket objects across network connections.
Syntax
DatagramSocket socket = new DatagramSocket(); // for sending DatagramSocket socket = new DatagramSocket(port); // for receiving
Methods of DatagramSocket
| Method | Description |
|---|---|
| send(DatagramPacket p) | Sends a UDP packet |
| receive(DatagramPacket p) | Receives a UDP packet |
| close() | Closes the socket |
| getPort() | Returns the port number |
| getInetAddress() | Returns the destination address |
| isClosed() | Checks if the socket is closed |
Example
UDP Server (Receiver)
import java.net.*;
public class UDPServer {
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);
System.out.println("Server is waiting...");
socket.receive(packet); // blocks until a packet is received
String message = new String(packet.getData(), 0, packet.getLength());
System.out.println("Received: " + message);
socket.close();
}
}
Example
UDP Client (Sender)
import java.net.*;
public class UDPClient {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
String message = "Hello, UDP Server!";
InetAddress address = InetAddress.getByName("localhost");
byte[] buffer = message.getBytes();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, 9876);
socket.send(packet);
System.out.println("Packet sent.");
socket.close();
}
}
Output
Server Console:
Server is waiting... Received: Hello, UDP Server!
Client Console:
Packet sent.
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com