Java - Socket Programming - User Datagram Protocol (UDP)

In this article let’s discuss about UDP Socket programming in Java.

Socket :

A socket is an endpoint for communication between two different machines. An application program can send/receive messages from a socket. Each socket has a port associated with it.

Socket Programming in java is used for inter process communication between two processes (programs) running in two different machines. There are two basic protocols can be used to transmitting the message.

1.) TCP/IP - Connection-Oriented Protocol
2.) UDP - Connection-less Protocol (You need to send the sender address for every packet transmitted).

Let’s consider a simple Client-Server model program to demonstrate the UDP Socket programming in java.

UDP

Using User Datagram Protocol, Applications can send data/message to the other hosts without prior communications or channel or path. This means even if the destination host is not available, application can send data. There is no guarantee that the data is received in the other side. Hence it's not a reliable service.

UDP is appropriate in places where delivery of data doesn't matters during data transition.

In this section, Let us see how to implement a simple Client Server UDP Communication using Datagram Sockets.

UDPServer Implementation

/**
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE IS DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package in.techdive.udp.server;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * UDP Server listening to receive data from UDP Clients
 */

public class UDPServer
{
        public static void main(String args[])
        {
                int server_port = 1111;
                System.out.println("UDP Server Listening in " + server_port);
                try
                {
                        // DatagramSocket created and listening in Port 1111
                        DatagramSocket socket = new DatagramSocket(server_port);
                        byte[] msgBuffer = new byte[1024];

                        // DatagramPacket for receiving the incoming data from UDP Client
                        DatagramPacket packet = new DatagramPacket(msgBuffer, msgBuffer.length);

                        while (true)
                        {
                                socket.receive(packet);
                                String message = new String(msgBuffer, 0, packet.getLength());
                                System.out.println("UDPServer: Message received = " + message);
                                packet.setLength(msgBuffer.length);
                        }
                }
                catch (Exception e)
                {
                        e.printStackTrace();
                        System.out.println("Error in getting the Data from UDP Client");
                }
        }
}

UDPClient Implementation

/**
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE IS DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package in.techdive.udp.client;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * UDP Client for sending message
 */

public class UDPClient
{
        public static void main(String args[])
        {
                try
                {
                        String server_address = "localhost";
                        int server_port = 1111;
                        String message = "Techdive.in";

                        InetAddress address = InetAddress.getByName(server_address);

                        // Create Datagram packet with the UDP Server Ipaddress/ Port and Message to be sent
                        DatagramPacket packet = new DatagramPacket(message.getBytes(), message.getBytes().length, address, server_port);

                        // Create DatagramSocket socket and send the Message
                        DatagramSocket socket = new DatagramSocket();
                        socket.send(packet);
                        System.out.println("UDPClient: Sent data to Server ; Message = " + message);
                        socket.close();
                }
                catch (Exception e)
                {
                        e.printStackTrace();
                        System.out.println("Error in sending the Data to UDP Server");
                }
        }
}

Testing
In order to test the above UDP Client and Server, perform the below steps,

1. Execute the UDPServer.java class.
This will create the Datagram Socket and it will listen continuously in the port 1111.

2. Execute the UDPClient.java class which will send the data using Datagram Socket to the local host in port 1111.

Output

UDP Server Listening in 1111
UDPServer: Message received = Techdive.in
Technology: 

Search