Open In App

Java.net.DatagramSocket class in Java

Improve
Improve
Like Article
Like
Save
Share
Report

Datagram socket is a type of network socket which provides connection-less point for sending and receiving packets. Every packet sent from a datagram socket is individually routed and delivered. It can also be used for sending and receiving broadcast messages. Datagram Sockets is the java’s mechanism for providing network communication via UDP instead of TCP. 

Constructors :  

1. DatagramSocket() : Creates a datagramSocket and binds it to any available port on local machine. If this constructor is used, the OS would assign any port to this socket. 

Syntax :public DatagramSocket()
               throws SocketException
Throws :
SocketException : if the socket could not be opened

2. DatagramSocket(DatagramSocketImpl impl) : Creates an unbound datagram socket with given datagramImpl. 

Syntax :protected DatagramSocket(DatagramSocketImpl impl)
Parameters :
impl : instance of datagramScketImpl

3. DatagramSocket(int port) : Creates and binds the datagram socket to the specified port. The socket will be bound to the a wildcard address chosen by kernel. 

Syntax : public DatagramSocket(int port)
               throws SocketException
Parameters : 
port : port number to bind this socket to

4. DatagramSocket(int port, InetAddress laddr) : Constructs a datagram socket and binds it to specified port and inetaddress. 

Syntax : public DatagramSocket(int port,
              InetAddress laddr)
               throws SocketException
Parameters :
port : local port to bind
laddr : local address to bind
Throws :
SocketException : If the socket could not be opened

5. DatagramSocket(SocketAddress bindaddr) : Constructs a new socket object and binds it the specified socket address(IP address+port number). 

Syntax :public DatagramSocket(SocketAddress bindaddr)
               throws SocketException
Parameters :
bindaddr : socket address to bind to
Throws : 
SocketException : If socket could not be opened

Methods : 

1. bind() : Binds this socket to specified address and port number. 

Syntax : public void bind(SocketAddress addr)
Parameters : 
addr : socket address to bind to

2. connect() : Connects to the specified address and port. After connecting to the remote host, this socket can send or receive packet from this remote host only. If a connection cannot be made to the specified remote host, the calls to send() or receive() would throw PortUnreachable Exception. 

Syntax :public void connect(InetAddress address,
           int port)
Parameters :
address : address of remote host
port : port number of remote host

Another overloaded method takes socket address as a parameter. 

Syntax :public void connect(SocketAddress address)
Parameters :
address : socket address of remote host

3. disconnect() : Disconnects the socket. If the socket is not connected, then this method has no effect. 

Syntax :public void disconnect()

4. isBound() : Returns a boolean value indicating whether this socket is bound or not. 

Syntax :public boolean isBound()

isConnected() : Returns a boolean value indicating whether this socket is connected or not. 

Syntax :public boolean isConnected()

5. isConnected() : Returns boolean value representing connection state of the socket. Please note that even after closing the socket, this method will continue to return true if this socket was connected prior to closing the socket. 

Syntax :public boolean isConnected()

6. getInetAddress() : Returns the address to which this socket is connected. 

Syntax : public InetAddress getInetAddress()

7. getPort() : Returns the port on the machine to which this socket is connected. 

Syntax : public int getPort()

8. getRemoteSocketAddress() : Returns the socket address (IP address+port number) to which this socket is connected. 

Syntax : public SocketAddress getRemoteSocketAddress()

9. getLocalSocketAddress() : Returns the address of the machine this socket is bound to, i.e. local machine socket address. 

public SocketAddress getLocalSocketAddress()

10. send() : Sends a datagram packet from this socket. It should be noted that the information about the data to be sent, the address to which it is sent etc are all handled by the packet itself. 

Syntax : public void send(DatagramPacket p)
Parameters :
p : packet to send

11. receive() : It is used to receive the packet from a sender. When a packet is successfully received, the buffer of the packet is filled with received message. The packet also contains valuable information like the senders address and the port number. This method waits till a packet is received. 

Syntax : public void receive(DatagramPacket p)
Parameters : 
p : datagram packet into which incoming data is filled

12. getLocalAddress() : Returns the local address to which this socket is bound. 

Syntax : public InetAddress getLocalAddress()

13. getLocalPort() : Returns the port on local machine to which this socket is bound. 

Syntax : public int getLocalPort()

14. setSOTimeout() : This is used to set the waiting time for receiving a datagram packet. As a call to receive() method blocks execution of the program indefinitely until a packet is received, this method can be used to limit that time. Once the time specified expires, java.net.SocketTimeoutException is thrown. 

Syntax : public void setSoTimeout(int timeout)
Parameters :
timeout : time to wait

15. getSoTimeout() : Returns the timeout parameter if specified, or 0 which indicates infinite time. 

Syntax : public int getSoTimeout()

16. setSendBufferSize() : Used to set a limit to maximum size of the packet that can be sent from this socket. It sets the SO_SNDBUF option, which is used by network implementation to set size of underlying network buffers. Increasing the size may allow to queue the packets before sending when send rate is high. 

Syntax : public void setSendBufferSize(int size)
Parameters : 
size : size of send buffer to set

Java Implementation :

Java




import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Arrays;
   
public class datasocket 
{
    public static void main(String[] args) throws IOException 
    {
        // Constructor to create a datagram socket
        DatagramSocket socket = new DatagramSocket();
        InetAddress address = InetAddress.getByName("localhost");
        int port = 5252;
        byte buf[] = { 12, 13 };
        byte buf1[] = new byte[2];
        DatagramPacket dp = new DatagramPacket(buf, 2, address, port);
        DatagramPacket dptorec = new DatagramPacket(buf1, 2);
           
        // connect() method
        socket.connect(address, port);
       
        // isBound() method
        System.out.println("IsBound : " + socket.isBound());
   
        // isConnected() method
        System.out.println("isConnected : " + socket.isConnected());
   
        // getInetAddress() method
        System.out.println("InetAddress : " + socket.getInetAddress());
   
        // getPort() method
        System.out.println("Port : " + socket.getPort());
   
        // getRemoteSocketAddress() method
        System.out.println("Remote socket address : "
                         socket.getRemoteSocketAddress());
   
        // getLocalSocketAddress() method
        System.out.println("Local socket address : "
                          socket.getLocalSocketAddress());
   
        // send() method
        socket.send(dp);
        System.out.println("...packet sent successfully....");
   
        // receive() method
        socket.receive(dptorec);
        System.out.println("Received packet data : "
                          Arrays.toString(dptorec.getData()));
   
        // getLocalPort() method
        System.out.println("Local Port : " + socket.getLocalPort());
   
        // getLocalAddress() method
        System.out.println("Local Address : " + socket.getLocalAddress());
   
        // setSOTimeout() method
        socket.setSoTimeout(50);
   
        // getSOTimeout() method
        System.out.println("SO Timeout : " + socket.getSoTimeout());
    }
   
}


To test the above program, a small server program is required for receiving the sent packet and for implementing receive() method. Its implementation is given below.

Java




import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class smallserver {
   
    public static void main(String[] args) throws IOException {
           
        DatagramSocket ds = new DatagramSocket(5252);
        byte buf[] = new byte[2];
        byte send[] = { 13, 18 };
        DatagramPacket dp = new DatagramPacket(buf, 2);
   
        ds.receive(dp);
   
        DatagramPacket senddp = new DatagramPacket(send, 2
                               dp.getAddress(), dp.getPort());
        ds.send(senddp);
    }
   
}


Output: On the client-side

IsBound : true
isConnected : true
InetAddress : localhost/127.0.0.1
Port : 5252
Remote socket address : localhost/127.0.0.1:5252
Local socket address : /127.0.0.1:59498
packet sent successfully
Received packet data : [13, 18]
Local Port : 59498
Local Address : /127.0.0.1
SO Timeout : 50

17. getSendBufferSize() : Returns the value of SO_SNDBUF option of this socket. 

Syntax : public int getSendBufferSize()

18. setReceiveBufferSize() : Used to set a limit to maximum size of the packet that is received on this socket. It sets the SO_RCVBUF option, which is used by network implementation to set size of underlying network buffers. Increasing the size may allow to queue the packets on receiving end when packets are sent faster than they are consumed. 

Syntax : public void setReceiveBufferSize(int size)
Parameters : 
size : size of receive buffer to set

19. getReceiveBufferSize() : Returns the value of SO_RCVBUF option of this socket. 

Syntax : public int getReceiveBufferSize()

20. setReuseAddress() : Sometimes it may be necessary to bind multiple sockets to the same address. Enabling this option enables other socket to bind to same address as this. It must be set before a call to bind() is made. It sets the value of SO_REUSEADDR socket option. 

Syntax : public void setReuseAddress(boolean on)
Parameters : 
on : true for enable, false otherwise

21. getReuseAddress() : Returns boolean value indicating the setting of SO_REUSEADDR socket option. 

Syntax : public boolean getReuseAddress()

22. setBroadcast() : Sets the value of SO_BROADCAST socket option. 

Syntax : public void setBroadcast(boolean on)
Parameters : 
on : true to allow broadcast, false otherwise

23. getBroadcast() : Returns true if broadcast is enabled, false otherwise. 

Syntax : public boolean getBroadcast()

24. setTrafficClass() : used to set the type-of-service octet in the IP datagram header for datagrams sent from this DatagramSocket. For more details about traffic, class refer to Wikipedia 

Syntax : public void setTrafficClass(int tc)
Parameters : 
tc : int value of bitset, 0<=tc<=255

25. getTrafficClass() : Gets traffic class or type of service from the IP header of packets sent from this socket. 

Syntax : public int getTrafficClass()

26. close() : Closes this datagram socket. Any pending receive call will throw SocketException. 

Syntax : public void close()

27. isClosed() : Returns the boolean value indicating if the socket is closed or not. 

Syntax : public boolean isClosed()

28. getChannel() : Returns a data channel if any associated with this socket. More details about Datagram channels can be found on Official Java Documentation

Syntax : public DatagramChannel getChannel()

29. setDatagramSocketImplFactory() : Sets the datagram socket implementation factory for the application. 

Syntax :public static void setDatagramSocketImplFactory(
                                 DatagramSocketImplFactory fac)
Parameters : 
fac - the desired factory.
Throws : 
IOException - if an I/O error occurs when setting the datagram socket factory.
SocketException - if the factory is already defined.

Java Implementation :

Java




import java.io.IOException;
import java.net.DatagramSocket;
   
public class datasock2 {
   
    public static void main(String[] args) throws IOException {
   
        // Constructor
        DatagramSocket socket = new DatagramSocket(1235);
   
        // setSendBufferSize() method
        socket.setSendBufferSize(20);
   
        // getSendBufferSize() method
        System.out.println("Send buffer size : "
                         socket.getSendBufferSize());
   
        // setReceiveBufferSize() method
        socket.setReceiveBufferSize(20);
   
        // getReceiveBufferSize() method
        System.out.println("Receive buffer size : "
                           socket.getReceiveBufferSize());
   
        // setReuseAddress() method
        socket.setReuseAddress(true);
   
        // getReuseAddress() method
        System.out.println("SetReuse address : "
                             socket.getReuseAddress());
   
        // setBroadcast() method
        socket.setBroadcast(false);
   
        // getBroadcast() method
        System.out.println("setBroadcast : "
                              socket.getBroadcast());
   
        // setTrafficClass() method
        socket.setTrafficClass(45);
   
        // getTrafficClass() method
        System.out.println("Traffic class : "
                           socket.getTrafficClass());
   
        // getChannel() method
        System.out.println("Channel : "
       ((socket.getChannel()!=null)?socket.getChannel():"null"));
   
        // setSocketImplFactory() method
        socket.setDatagramSocketImplFactory(null);
   
        // close() method
        socket.close();
   
        // isClosed() method
        System.out.println("Is Closed : " + socket.isClosed());
   
    }
}


Output :

Send buffer size : 20
Receive buffer size : 20
SetReuse address : true
setBroadcast : false
Traffic class : 44
Channel : null
Is Closed : true

References: Official Java Documentation 

 



Last Updated : 30 Nov, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads