Skip to main content

UDP Client and Server program in Java

UDP:
Contrary to TCP, UDP is connection less and unreliable protocol. Connection less means before sending data we do not establish the connection between server and client, we just send the data right away.
This protocol is unreliable because when the data do not reach the destination, this protocol will not let the sender know about it. Then obviously one question arises : Then why we have such protocol ?

The answer is very simple, there are certain situation where we use UDP because of its speed.

  1. In Telecommunication: As UDP is very fast, we just want the voice to reach and little bit of data loss do not hamper the call.
  2. In DNS UDP is used.
  3. In transmitting multicast packets.



The below code simulation shows how UDP server and client work..
Client sends some alphabets to server and server returns them in sorted order.


UDP Server Code:
import java.io.IOException;
import java.net.*;
import java.util.Arrays;


public class UDPServer {
    public static void main(String args[]) throws Exception
    {
          DatagramSocket serverSocket = new DatagramSocket(1027); // open UDP socket
          serverSocket.setSoTimeout(100000); // setting time out for server socket
          
          byte[] receiveData = new byte[1024];  // to receive data
          byte[] sendData = new byte[1024];     // to send data
          
          System.out.println("UDP Server Started..");
          while(true)  // to listen the client continuously
             {
                try
                {
                    
                    DatagramPacket receivePacket = 
                                       new DatagramPacket(receiveData, receiveData.length);
                    serverSocket.receive(receivePacket); // blocks until packet is received
                    
                    String data = new String( receivePacket.getData());
                    System.out.println("RECEIVED: " + data);
                    // getting ip address of client
                    InetAddress IPAddress = receivePacket.getAddress(); 
                    int port = receivePacket.getPort(); // getting port of client
                    
                    //sort data 
                    data = data.replaceAll(" ", "");
                     
                    char[] arr = data.trim().toCharArray();
                    Arrays.sort(arr);
                     
                    data = "";
                    for(char c: arr) data += c;
                    System.out.println("SENDING: " + data);
                    //sending data back to client
                    sendData = data.getBytes();
                    DatagramPacket sendPacket = 
                           new DatagramPacket(sendData, sendData.length, IPAddress, port);
                    serverSocket.send(sendPacket);
                     
                }
                catch(SocketTimeoutException s)
                {
                    System.out.println("UDP Socket timed out!");
                    serverSocket.close();
                    break;
                }
                catch(IOException e)
                {
                   e.printStackTrace();
                   break;
                }
             }
   }
}

The code is self descriptive, read the comments in the code.


UDP Client Code:

import java.net.*;

public class UDPClient {
    public static void main(String[] args) throws Exception {

        // Creating socket
        DatagramSocket clientSocket = new DatagramSocket();

        // Getting server ip address
        InetAddress IPAddress = InetAddress.getByName("localhost");

        // Arrays for sending and receiving data
        byte[] sendData = new byte[1024];
        byte[] receiveData = new byte[1024];


        // Sending data to server
        String payload = "Z X C V B N M A S D F G";
        sendData = payload.getBytes();
         
        // preparing header
        DatagramPacket sendPacket = 
             new DatagramPacket(sendData, sendData.length, IPAddress, 1027); 
        clientSocket.send(sendPacket); // sending data

        // Getting data from sever
        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
        clientSocket.receive(receivePacket); // receiving data
        String dataFromSever = new String(receivePacket.getData());

        System.out.println("FROM SERVER:" + dataFromSever);

        clientSocket.close(); // close connection
    }
}




What is socket: 
Socket is combination of port number and ip address. It is used to distinguish between different processes on a computer.
Meaning, using IP address we can just distinguish one computer but what about the different processes running inside. For that a combination of port and IP address is used.



How this program works:

First run UDP Server program then client program, you will get below output:

FROM SERVER:ABCDFGMNSVXZ


Comments

Popular posts from this blog

Goodness of Fit Test for normal and poisson distribution

Meaning of Goodness of fit test: We find out which distribution fits the sample data the most. And this is achieved using chi-square distribution (Snedecor and Cochran, 1989). How to apply: There are 4 steps to follow: State the hypothesis:  Data follows a distribution or not Criteria to reject null hypothesis: if Χ 2  > Χ 2 (k,1-α) then reject null hypothesis. Analyze sample data: Compute the chi-square value using below formula: ∑(Oi- Ei) 2 /Ei        : Oi is observed frequency and Ei is expected frequency Interpret the results: Declare the results after comparing the values of Χ 2 and Χ 2 (k,1-α), where k is degree of freedom and  α is significance level. Degree of Freedom: It is  =  n - 1 - m m: number of parameter in the distribution. So in case of normal distribution m is 2 ( μ ,α) and in case of poisson dist. m is = 1 ( λ). Example 1: Goodness of fit test for Normal Distribution Year wise data is given about number of car accidents, find out w

classification of database indexing

Dense Index: For every records we are having one entry in the index file. Sparse Index: Only one record for each block we will have it in the index file. Primary Index ( Primary Key + Ordered Data )  A primary index is an ordered file whose records are fixed length size with 2 fields. First field is same as primary key and the second field is pointer to the data block.  Here index entry is created for first record of each block, called ‘block anchor’. Number of index entries thus are equal to number of blocks Average number of block accesses are = logB (worst case) + 1 (best case),  So on average it will be O(logB) The type of index is called sparse index because index is not created for all the records, only the first records of every block the entry is made into the index file. Example on Primary Index Number of Records = 30000, Block Size = 1024 Bytes, Strategy = Unspanned, Record Size = 100 Bytes, Key Size = 6 Bytes, Pointer Size = 9 Bytes, Then find avera

Red Black Tree Insertion in Java

Red Black Tree is a binary search tree. With extra property with each node having color either RED or BLACK. It has following properties: Every node is either RED or BLACK Root element will have BLACK color. Every RED node has BLACK children. Every path from root to leaf will have same number of BLACK nodes. We have few theorems over RB tree: Note: Height of RB tree is θ(logn). Insertion: Insertion in RB tree is little tricky as compared to BST, we have following cases to insert a node in RB tree: When tree is null just insert the node and it will be root, color will be BLACK. To insert an element first find its position: if key <= node.key then move to left else move to right Once we find the correct place to insert, we insert the node with color RED. But if the parent of the node just inserted has color RED then it will violate 3 property. So we have to fix this issue. We call it double RED problem, we resolve it using following few cases. DOUBLE R