Write A Java Program For Congestion Control Using Leaky Bucket Algorithm

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Write a Java program for congestion control using leaky bucket algorithm.

The leaky-bucket algorithm:


The algorithm can be conceptually understood as follows:
• Consider a bucket with a hole in the bottom.
• The empty space of the bucket represents an amount of credit available
measured in bytes.
• The size of the bucket is b bytes. This means that if the bucket
is empty, b bytes of credit is available.
• If a packet arrives and its size is less than the available
credit, the packet can be forwarded. Otherwise, it is
discarded or queued depending on the application.
• The bucket leaks through the hole in its bottom at a constant
rate of r bytes per second, this indicates credit accumulation

import java.util.Scanner;

public class LeakyBucket {


public static void main(String args[]) {
// Create a Scanner object for user input
Scanner sc = new Scanner(System.in);

// Declare variables to store parameters and simulation values


int incoming, outgoing, buck_size, n, time = 1, store = 0;

// Prompt the user to enter bucket size, outgoing rate, and the number of packets
System.out.println("Enter bucket size, outgoing rate and Number of Packets:");
buck_size = sc.nextInt(); // Read bucket size
outgoing = sc.nextInt(); // Read outgoing rate
n = sc.nextInt(); // Read the number of packets to be simulated

// Simulation loop for handling incoming packets


while (n != 0) {
// Prompt the user to enter the size of the incoming packet at a specific time
System.out.println("Enter the incoming packet size at Time:" + (time++));
incoming = sc.nextInt(); // Read the incoming packet size

// Display the incoming packet size


System.out.println("Incoming packet size is " + incoming);

// Check if the incoming packet fits in the bucket


if (incoming <= (buck_size - store)) {
// If it fits, add it to the bucket
store += incoming;
} else {
// If it doesn't fit, consider the excess as dropped
int pktdrop = incoming - (buck_size - store);
System.out.println("Dropped " + pktdrop + " no of packets");
System.out.println("Bucket buffer size is 10 out of " + buck_size);
store = buck_size; // Reset the bucket size to its maximum
}

// Subtract outgoing packets from the bucket


store = store - outgoing;

// If the bucket becomes empty, display a message


if (store < 0) {
store = 0;
System.out.println("Empty Buffer");
}

// Display the number of packets left in the buffer after outgoing


System.out.println("After outgoing: " + store + " packets left out of " +
buck_size + " in buffer\n");

// Decrement the number of packets to be simulated


n--;
}

// Close the Scanner object to prevent resource leaks


sc.close();
}
}

You might also like