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
{
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 );
socket.connect(address, port);
System.out.println( "IsBound : " + socket.isBound());
System.out.println( "isConnected : " + socket.isConnected());
System.out.println( "InetAddress : " + socket.getInetAddress());
System.out.println( "Port : " + socket.getPort());
System.out.println( "Remote socket address : " +
socket.getRemoteSocketAddress());
System.out.println( "Local socket address : " +
socket.getLocalSocketAddress());
socket.send(dp);
System.out.println( "...packet sent successfully...." );
socket.receive(dptorec);
System.out.println( "Received packet data : " +
Arrays.toString(dptorec.getData()));
System.out.println( "Local Port : " + socket.getLocalPort());
System.out.println( "Local Address : " + socket.getLocalAddress());
socket.setSoTimeout( 50 );
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 {
DatagramSocket socket = new DatagramSocket( 1235 );
socket.setSendBufferSize( 20 );
System.out.println( "Send buffer size : " +
socket.getSendBufferSize());
socket.setReceiveBufferSize( 20 );
System.out.println( "Receive buffer size : " +
socket.getReceiveBufferSize());
socket.setReuseAddress( true );
System.out.println( "SetReuse address : " +
socket.getReuseAddress());
socket.setBroadcast( false );
System.out.println( "setBroadcast : " +
socket.getBroadcast());
socket.setTrafficClass( 45 );
System.out.println( "Traffic class : " +
socket.getTrafficClass());
System.out.println( "Channel : " +
((socket.getChannel()!= null )?socket.getChannel(): "null" ));
socket.setDatagramSocketImplFactory( null );
socket.close();
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.InetSocketAddress class in Java
This class implements IP socket address( combination of IP address and port number). The objects of this class are immutable and can be used for binding, connecting purposes. Constructors : 1. InetSocketAddress(InetAddress addr, int port) : This constructor is similar to the general structure of a s
4 min read
Java.net.Inet4Address class in Java
This class extends the InetAddress class and represents an IPv4 address. It provides methods to interpret and display useful information about IP addresses. Methods of this class take input in 4 formats: d.d.d.d: When this format is used as input, each of the given values are assigned to 4 bytes of
3 min read
Java.net.InterfaceAddress class in Java
This class represents a network interface address. Every device that has an IP address has an IP address on the network interface. In fact the ping command doesn't ping a device but the devices interface address. Java provides certain methods to deal with interface addresses which can be used in pla
2 min read
Datagrams in Java
TCP/IP-style networking provides a serialized, predictable, reliable stream of packet data. This is not without its cost, however. TCP includes algorithms for dealing with congestion control on crowded networks, as well as pessimistic expectations about packet loss. This leads to inefficient way to
7 min read
Java.net.MulticastSocket class in Java
This class is used for sending and receiving multicast IP packets. It extends DatagramSocket class and provides additional functionality for joining groups. A message sent to the group IP address will be received by all the clients who have joined the group. This must be kept in mind that for sendin
6 min read
Bytes Class | Guava | Java
Bytes is a utility class for primitive type byte. It provides Static utility methods pertaining to byte primitives, that are not already found in either Byte or Arrays and interpret bytes as neither signed nor unsigned. The methods which specifically treat bytes as signed or unsigned are found in Si
3 min read
Introducing Threads in Socket Programming in Java
Prerequisites : Socket Programming in Java This article assumes that you have basic knowledge of socket programming in java and the basic details of client-server model used in communication. Why to use threads in network programming? The reason is simple, we don't want only a single client to conne
7 min read
Message encryption and decryption using UDP server
The process of message encryption and decryption during client-server communication using UDP server is as follows: The client requests the server with a file name.The corresponding file is opened by the server and sends the file using datagram socket.The sender sends the encrypted text (Xoring) wit
3 min read
Explicitly assigning port number to client in Socket
Prerequisite: Socket programming in C/C++.In socket programming, when server and client are connected then the client is provided any random port number by an operating system to run and generally, we don't care about it, But in some cases, there may be a firewall on the client-side that only allows
4 min read