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.

 

notepad

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.




Onlinetpoint is optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.