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
Similar Reads
Java.net.DatagramPacket class in Java
This class provides facility for connection less transfer of messages from one system to another. Each message is routed only on the basis of information contained within the packet and it may be possible for different packets to route differently. There is also no guarantee as to whether the messag
5 min read
Java.net.HttpURLConnection Class in Java
HttpURLConnection class is an abstract class directly extending from URLConnection class. It includes all the functionality of its parent class with additional HTTP-specific features. HttpsURLConnection is another class that is used for the more secured HTTPS protocol. It is one of the popular choi
5 min read
Java.io.DataInputStream class in Java | Set 1
A data input stream enables an application to read primitive Java data types from an underlying input stream in a machine-independent way(instead of raw bytes). That is why it is called DataInputStream - because it reads data (numbers) instead of just bytes. An application uses a data output stream
3 min read
Java.io.DataInputStream class in Java | Set 2
Java.io.DataInputStream class in Java | Set 1 More Methods: byte readByte() : Reads and returns one input byte. Syntax:public final byte readByte() throws IOException Returns: the next byte of this input stream as a signed 8-bit byte. Throws: EOFException IOException float readFloat() : Reads four i
3 min read
Java.net.JarURLConnection class in Java
Prerequisite - JAR files in Java What is a Jar file? JavaArchive(JAR) bundles all the classes in one package. Since the archive is compressed and can be downloaded in a single HTTP connection, it is often faster to download the archive than to download individual classes. Although jar bundles all th
4 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It
15+ min read
java.net.Proxy Class in Java
A proxy is an immutable object and type of tool or application or program or system, which helps to protect the information of its users and computers. It acts as a barrier between computer and internet users. A Proxy Object defines the Proxy settings to be used with a connection. Proxy servers are
3 min read
java.nio.FloatBuffer Class in Java
A Buffer object can be termed as a container for a fixed amount of data. The buffer acts as a storing box, or temporary staging area, where data can be stored and later retrieved according to the usage. Java Buffer classes are the foundation or base upon which java.nio is built. Float buffers are cr
4 min read
java.net.InetAddress Class in Java
public class InetAddress extends Object implements Serializable: The java.net.InetAddress class provides methods to get the IP address of any hostname. An IP address is represented by 32-bit or 128-bit unsigned number. InetAddress can handle both IPv4 and IPv6 addresses. There are 2 types of address
6 min read
java.net.Socket Class in Java
The java.net.Socket class allows us to create socket objects that help us in implementing all fundamental socket operations. We can perform various networking operations such as sending, reading data and closing connections. Each Socket object that has been created using with java.net.Socket class h
5 min read