Advanced Java Programming - Old Questions

9. What is socket? Differentiate TCP socket from UDP socket.

5 marks | Asked in 2072

Sockets are the endpoints of logical connections between two hosts and can be used to send and receive data. Java supports stream sockets and datagram sockets.

Datagram sockets use UDP (User Datagram Protocol) for data transport, thus they are also called UDP socketsStream sockets use TCP (Transmission Control Protocol) for data transport, thus they are also called TCP sockets.  Since TCP can detect lost transports and resubmit them, the transports are lossless and reliable. UDP, in contrast, cannot guarantee lossless transport and so is unreliable.

TCP

UDP

TCP is a connection oriented protocol.

UDP is a connectionless oriented protocol.

TCP assure reliable delivery of data to the destination.

UDP does not assure reliable delivery of data to the destination.

TCP provides extensive error checking mechanisms such as flow control and acknowledgement of data.

UDP does not provides error checking mechanisms such as flow control and acknowledgement of data.

Delivery of data is guaranteed if you are using TCP.

Delivery of data is not guaranteed if you are using UDP.

TCP is comparatively slow because of these extensive error checking mechanism.

UDP makes fast and best effort service to transmit data.

Retransmission of lost packets is possible.

There is no retransmission of lost packets in UDP.


The Java code to perform client-server communication using UDP sockets is given below:


//UDPClient.java

import java.net.*;

import java.io.*;

public class UDPClient

{

    public static void main (String[] args)

    {

        try

        {

            DatagramSocket socket = new DatagramSocket ();

            byte[] buf = new byte[256];      //Byte array to store information

            String messg = "Hello UDP Server\\n";

            buf = messg.getBytes ();    //Getting the size of message

            InetAddress address = InetAddress.getByName ("127.0.0.1");

            DatagramPacket packet = new DatagramPacket (buf, buf.length, address, 1234);

            socket.send(packet);         // Sends datagram packet, packet

        }

        catch (IOException e)

        {

        }

    }

}


//UDPServer.java

import java.net.*;

import java.io.*;

public class UDPServer

{

    public static void main (String[] args)

    {

        try

        {

            DatagramSocket socket = new DatagramSocket (1234);

            byte[] buf = new byte[256];

            DatagramPacket packet = new DatagramPacket (buf, buf.length);

            socket.receive (packet);

            String received = new String (packet.getData());

            System.out.println ("Received packet: " + received);

        }

        catch (IOException e)

        {

        }     

    }

}