1.
Write a program to design a TCP Client-Server application to transfer a
file.
b) Using TCP socket download a webpage and get the URL and pass it
for buffering the content and write it as a html file
import java.io.*;
import java.net.*;
public class TCPFileServer {
public static void main(String[] args) {
int port = 12345;
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("Server listening on port " + port);
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket.getInetAddress());
// Input stream to receive file data from the client
DataInputStream inputStream = new
DataInputStream(clientSocket.getInputStream());
// Read the file name sent by the client
String fileName = inputStream.readUTF();
System.out.println("Receiving file: " + fileName);
// Output stream to save the received file
FileOutputStream fileOutputStream = new FileOutputStream("received_"
+ fileName);
// Read file data and write to the output file
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
System.out.println("File received and saved as received_" + fileName);
// Close the connections
fileOutputStream.close();
inputStream.close();
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.*;
import java.net.*;
public class TCPFileClient {
public static void main(String[] args) {
String serverAddress = "localhost";
int port = 12345;
String filePath = "sample.txt"; // Replace with the file you want to send
try (Socket socket = new Socket(serverAddress, port)) {
// Input stream to read the file
FileInputStream fileInputStream = new FileInputStream(filePath);
DataOutputStream outputStream = new
DataOutputStream(socket.getOutputStream());
// Send the file name to the server
File file = new File(filePath);
outputStream.writeUTF(file.getName());
// Send the file content to the server
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("File sent successfully!");
// Close streams
fileInputStream.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
TCP Webpage Downloader (Client)
Java
import java.io.*;
import java.net.*;
public class TCPWebPageDownloader {
public static void main(String[] args) {
String urlString = "http://example.com"; // URL to download
String host = "example.com"; // Hostname to connect to
int port = 80; // HTTP port (default is 80)
try (Socket socket = new Socket(host, port);
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()))) {
// Send an HTTP GET request to the server
writer.println("GET / HTTP/1.1");
writer.println("Host: " + host);
writer.println("Connection: close");
writer.println();
// Read the response (HTML content)
String line;
StringBuilder responseContent = new StringBuilder();
while ((line = reader.readLine()) != null) {
responseContent.append(line).append("\n");
}
// Write the content to an HTML file
try (BufferedWriter fileWriter = new BufferedWriter(new
FileWriter("downloaded_page.html"))) {
fileWriter.write(responseContent.toString());
System.out.println("Webpage downloaded and saved as
downloaded_page.html");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2Write a program to implement the TCP Client Server Chat
Application using Sockets
TCP Server for Chat Application
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
private static Set<PrintWriter> clientWriters = new
HashSet<>();
private static int clientCount = 0;
public static void main(String[] args) {
int port = 12345;
System.out.println("Chat Server started on port " + port);
try (ServerSocket serverSocket = new ServerSocket(port)) {
while (true) {
// Accept incoming client connections
Socket clientSocket = serverSocket.accept();
System.out.println("New client connected");
// Create a new thread for each client
new ClientHandler(clientSocket).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// Inner class to handle client connections and communication
private static class ClientHandler extends Thread {
private Socket socket;
private PrintWriter out;
private BufferedReader in;
public ClientHandler(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
// Set up input and output streams for the client
in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
synchronized (clientWriters) {
clientWriters.add(out);
}
String message;
while ((message = in.readLine()) != null) {
if (message.equalsIgnoreCase("exit")) {
break;
}
System.out.println("Received: " + message);
// Broadcast message to all clients
synchronized (clientWriters) {
for (PrintWriter writer : clientWriters) {
writer.println("Client " + ++clientCount + ": " +
message);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
synchronized (clientWriters) {
clientWriters.remove(out);
}
System.out.println("Client disconnected");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
TCP Client for Chat Application
import java.io.*;
import java.net.*;
public class ChatClient {
private static final String SERVER_ADDRESS = "localhost";
private static final int SERVER_PORT = 12345;
private static BufferedReader consoleReader;
private static PrintWriter serverWriter;
public static void main(String[] args) {
try (Socket socket = new Socket(SERVER_ADDRESS,
SERVER_PORT)) {
consoleReader = new BufferedReader(new
InputStreamReader(System.in));
serverWriter = new PrintWriter(socket.getOutputStream(),
true);
// Start a thread to listen for messages from the server
new ServerListener(socket).start();
String message;
while (true) {
System.out.print("You: ");
message = consoleReader.readLine();
if (message.equalsIgnoreCase("exit")) {
serverWriter.println(message);
break;
}
serverWriter.println(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
// Inner class to handle incoming messages from the server
private static class ServerListener extends Thread {
private BufferedReader serverReader;
public ServerListener(Socket socket) {
try {
serverReader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
String message;
try {
while ((message = serverReader.readLine()) != null) {
System.out.println(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Output
Chat Server started on port 12345
New client connected
Received: Hello, everyone!
Client 1: Hello, everyone!
Client output
You: Hello, everyone!
Client 1: Hello, everyone!
Write a programs hello_server for TCP (The client connects to the
server, sends the string “Hello, world!”, then closes the
connection )
TCP Server Program (hello_server.java)
import java.io.*;
import java.net.*;
public class HelloServer {
public static void main(String[] args) {
int port = 12345;
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("Server is listening on port " + port);
// Wait for the client to connect
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket.getInetAddress());
// Create input stream to read data sent by the client
BufferedReader reader = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
// Read the message sent by the client
String message = reader.readLine();
System.out.println("Received from client: " + message);
// Close the connection
reader.close();
clientSocket.close();
System.out.println("Connection closed.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
TCP Client Program (hello_client.java)
import java.io.*;
import java.net.*;
public class HelloClient {
public static void main(String[] args) {
String serverAddress = "localhost"; // Address of the server
int port = 12345; // Port to connect to
try (Socket socket = new Socket(serverAddress, port)) {
// Create output stream to send data to the server
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
// Send the message "Hello, world!" to the server
writer.println("Hello, world!");
System.out.println("Message sent to server: Hello, world!");
// Close the connection
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
1. Output:
o Server:
Server is listening on port 12345
Client connected: /127.0.0.1
Received from client: Hello, world!
Connection closed.
o Client:
Message sent to server: Hello, world!
4.Write the program for Simulation of DNS using UDP
Socket by getting the frame size from the user and create
the frame sized user request and send the frame to server
from the client.
UDP Server Program (DNSServer.java)
import java.net.*;
public class DNSServer {
public static void main(String[] args) {
int port = 12345;
try (DatagramSocket serverSocket = new DatagramSocket(port)) {
System.out.println("DNS Server is listening on port " + port);
byte[] receiveData = new byte[1024]; // Buffer for receiving data
DatagramPacket receivePacket = new
DatagramPacket(receiveData, receiveData.length);
while (true) {
// Receive the client request
serverSocket.receive(receivePacket);
String clientRequest = new String(receivePacket.getData(), 0,
receivePacket.getLength());
System.out.println("Received request: " + clientRequest);
// Process the DNS request (this is just a simulation, so we'll
echo back the request)
String serverResponse = "DNS Response: " + clientRequest;
// Send the response back to the client
InetAddress clientAddress = receivePacket.getAddress();
int clientPort = receivePacket.getPort();
byte[] responseData = serverResponse.getBytes();
DatagramPacket sendPacket = new
DatagramPacket(responseData, responseData.length, clientAddress,
clientPort);
serverSocket.send(sendPacket);
System.out.println("Response sent to client: " +
serverResponse);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
UDP Client Program (DNSClient.java)
import java.net.*;
import java.util.Scanner;
public class DNSClient {
public static void main(String[] args) {
String serverAddress = "localhost"; // Server address (localhost for testing)
int serverPort = 12345; // Server port
try (DatagramSocket clientSocket = new DatagramSocket()) {
Scanner scanner = new Scanner(System.in);
// Get the frame size from the user
System.out.print("Enter the frame size (in bytes): ");
int frameSize = scanner.nextInt();
scanner.nextLine(); // Consume the newline character
// Generate a request frame with the specified size
StringBuilder requestFrame = new StringBuilder();
for (int i = 0; i < frameSize; i++) {
requestFrame.append("A"); // Fill the frame with 'A' characters
}
// Send the request frame to the server
byte[] requestData = requestFrame.toString().getBytes();
InetAddress serverAddressObj = InetAddress.getByName(serverAddress);
DatagramPacket sendPacket = new DatagramPacket(requestData,
requestData.length, serverAddressObj, serverPort);
clientSocket.send(sendPacket);
System.out.println("Request frame sent to server: " + requestFrame);
// Receive the response from the server
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
clientSocket.receive(receivePacket);
String serverResponse = new String(receivePacket.getData(), 0,
receivePacket.getLength());
System.out.println("Received response from server: " + serverResponse);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
Server output:
DNS Server is listening on port 12345
Received request: AAAAAAAAAA
Response sent to client: DNS Response: AAAAAAAAAA
Client output:
Enter the frame size (in bytes): 10
Request frame sent to server: AAAAAAAAAA
Received response from server: DNS Response: AAAAAAAAAA
5.a) Write a program to implement to transfer the files using
TCP socket. The server send a reply to the user with the files.
The user specified file needs to be downloaded.
b) Using Wireshark capture the FTP username and password
TCP File Transfer Server Program (FileServer.java)
java
Copy code
import java.io.*;
import java.net.*;
public class FileServer {
public static void main(String[] args) {
int port = 12345;
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("File server listening on port " + port);
while (true) {
// Accept client connections
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " +
clientSocket.getInetAddress());
// Handle the client in a new thread
new FileHandler(clientSocket).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// Inner class to handle file transfer with the client
private static class FileHandler extends Thread {
private Socket clientSocket;
public FileHandler(Socket clientSocket) {
this.clientSocket = clientSocket;
}
@Override
public void run() {
try (InputStream inputStream = clientSocket.getInputStream();
OutputStream outputStream = clientSocket.getOutputStream()) {
BufferedReader reader = new BufferedReader(new
InputStreamReader(inputStream));
// Receive the file name from the client
String fileName = reader.readLine();
System.out.println("Client requested file: " + fileName);
// Check if the requested file exists
File file = new File(fileName);
if (file.exists() && !file.isDirectory()) {
// Send the file to the client
byte[] buffer = new byte[4096];
FileInputStream fileInputStream = new FileInputStream(file);
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
fileInputStream.close();
System.out.println("File sent to client.");
} else {
System.out.println("File not found: " + fileName);
outputStream.write("File not found.".getBytes());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
TCP File Transfer Client Program (FileClient.java)
java
Copy code
import java.io.*;
import java.net.*;
public class FileClient {
public static void main(String[] args) {
String serverAddress = "localhost"; // Server address
int port = 12345; // Server port
try (Socket socket = new Socket(serverAddress, port);
BufferedReader consoleReader = new BufferedReader(new
InputStreamReader(System.in));
PrintWriter socketWriter = new PrintWriter(socket.getOutputStream(),
true);
InputStream socketInputStream = socket.getInputStream()) {
// Get the file name from the user
System.out.print("Enter the name of the file to download: ");
String fileName = consoleReader.readLine();
// Send the file name to the server
socketWriter.println(fileName);
// Receive the file data from the server
FileOutputStream fileOutputStream = new
FileOutputStream("downloaded_" + fileName);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = socketInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
fileOutputStream.close();
System.out.println("File downloaded as downloaded_" + fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
}
6.Simulate the Reverse Address Resolution Protocol (RARP) using
UDP
RARP Server Program (RARPServer.java)
java
Copy code
import java.net.*;
import java.util.HashMap;
import java.util.Map;
public class RARPServer {
public static void main(String[] args) {
int port = 12345; // The port to listen on
Map<String, String> macToIpMap = new HashMap<>(); // Mapping of MAC
addresses to IP addresses
// Populating the MAC-to-IP mapping
macToIpMap.put("00:14:22:01:23:45", "192.168.1.10");
macToIpMap.put("00:15:5D:16:55:7B", "192.168.1.20");
macToIpMap.put("00:1A:2B:3C:4D:5E", "192.168.1.30");
try (DatagramSocket serverSocket = new DatagramSocket(port)) {
System.out.println("RARP Server is listening on port " + port);
byte[] receiveData = new byte[1024]; // Buffer to receive MAC address
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
while (true) {
// Receive the MAC address from the client
serverSocket.receive(receivePacket);
String clientMacAddress = new String(receivePacket.getData(), 0,
receivePacket.getLength()).trim();
System.out.println("Received MAC address: " + clientMacAddress);
// Look up the IP address corresponding to the MAC address
String ipAddress = macToIpMap.get(clientMacAddress);
// Prepare response message
String responseMessage;
if (ipAddress != null) {
responseMessage = "IP address for " + clientMacAddress + " is " +
ipAddress;
} else {
responseMessage = "MAC address not found in the mapping!";
}
// Send the response back to the client
InetAddress clientAddress = receivePacket.getAddress();
int clientPort = receivePacket.getPort();
byte[] responseData = responseMessage.getBytes();
DatagramPacket sendPacket = new DatagramPacket(responseData,
responseData.length, clientAddress, clientPort);
serverSocket.send(sendPacket);
System.out.println("Sent response: " + responseMessage);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
RARP Client Program (RARPClient.java)
java
Copy code
import java.net.*;
import java.util.Scanner;
public class RARPClient {
public static void main(String[] args) {
String serverAddress = "localhost"; // Server address
int serverPort = 12345; // Server port
try (DatagramSocket clientSocket = new DatagramSocket()) {
Scanner scanner = new Scanner(System.in);
// Get MAC address from the user
System.out.print("Enter MAC address (e.g., 00:14:22:01:23:45): ");
String macAddress = scanner.nextLine();
// Send the MAC address to the server
byte[] macAddressData = macAddress.getBytes();
InetAddress serverInetAddress = InetAddress.getByName(serverAddress);
DatagramPacket sendPacket = new DatagramPacket(macAddressData,
macAddressData.length, serverInetAddress, serverPort);
clientSocket.send(sendPacket);
System.out.println("Sent MAC address to server: " + macAddress);
// Receive the response from the server
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
clientSocket.receive(receivePacket);
String serverResponse = new String(receivePacket.getData(), 0,
receivePacket.getLength());
System.out.println("Server Response: " + serverResponse);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Server Output:
csharp
Copy code
RARP Server is listening on port 12345
Received MAC address: 00:14:22:01:23:45
Sent response: IP address for 00:14:22:01:23:45 is 192.168.1.10
Client Output:
less
Copy code
Enter MAC address (e.g., 00:14:22:01:23:45): 00:14:22:01:23:45
Sent MAC address to server: 00:14:22:01:23:45
Server Response: IP address for 00:14:22:01:23:45 is 192.168.1.10
7.Write a program to find the least cost route between any
two nodes using Distance Vector Routing algorithm.
DistanceVectorRouting.java
java
Copy code
import java.util.*;
public class DistanceVectorRouting {
static final int INF = Integer.MAX_VALUE; // Infinite distance
int numNodes;
int[][] distanceMatrix; // Matrix to store the costs
public DistanceVectorRouting(int numNodes) {
this.numNodes = numNodes;
distanceMatrix = new int[numNodes][numNodes];
// Initialize the distance matrix
for (int i = 0; i < numNodes; i++) {
for (int j = 0; j < numNodes; j++) {
if (i == j) {
distanceMatrix[i][j] = 0; // Cost to itself is 0
} else {
distanceMatrix[i][j] = INF; // Initially all other
distances are infinite
}
}
}
}
// Function to add an edge between two nodes
public void addEdge(int from, int to, int cost) {
distanceMatrix[from][to] = cost;
distanceMatrix[to][from] = cost; // Since the graph is
undirected
}
// Function to run the Distance Vector Routing algorithm
public void distanceVectorRouting() {
int[][] distanceVector = new int[numNodes][numNodes];
// Initialize the distance vector with the initial distances
for (int i = 0; i < numNodes; i++) {
for (int j = 0; j < numNodes; j++) {
distanceVector[i][j] = distanceMatrix[i][j];
}
}
// Perform the distance vector updates
boolean updated;
do {
updated = false;
for (int i = 0; i < numNodes; i++) {
for (int j = 0; j < numNodes; j++) {
if (i != j) {
for (int k = 0; k < numNodes; k++) {
if (distanceVector[i][j] > distanceVector[i][k]
+ distanceVector[k][j]) {
distanceVector[i][j] = distanceVector[i][k]
+ distanceVector[k][j];
updated = true;
}
}
}
}
}
} while (updated);
// Print the resulting distance vector
printDistanceVector(distanceVector);
}
// Function to print the distance vector (least cost paths)
public void printDistanceVector(int[][] distanceVector) {
System.out.println("Distance Vector (Least cost
routes):");
for (int i = 0; i < numNodes; i++) {
System.out.print("From Node " + i + " to: ");
for (int j = 0; j < numNodes; j++) {
if (distanceVector[i][j] == INF) {
System.out.print("INF ");
} else {
System.out.print(distanceVector[i][j] + " ");
}
}
System.out.println();
}
}
// Function to find the least cost route between two nodes
public int findLeastCostRoute(int startNode, int endNode) {
return distanceMatrix[startNode][endNode];
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Create a DistanceVectorRouting object with 5 nodes (0,
1, 2, 3, 4)
DistanceVectorRouting dvr = new
DistanceVectorRouting(5);
// Add edges to the network (undirected graph with
weights)
dvr.addEdge(0, 1, 10);
dvr.addEdge(0, 2, 20);
dvr.addEdge(1, 2, 5);
dvr.addEdge(1, 3, 15);
dvr.addEdge(2, 4, 30);
dvr.addEdge(3, 4, 10);
// Run the Distance Vector Routing algorithm
dvr.distanceVectorRouting();
// Query for least cost route between nodes
System.out.print("Enter start node: ");
int startNode = scanner.nextInt();
System.out.print("Enter end node: ");
int endNode = scanner.nextInt();
int cost = dvr.findLeastCostRoute(startNode, endNode);
if (cost == INF) {
System.out.println("No path exists between node " +
startNode + " and node " + endNode);
} else {
System.out.println("Least cost route from node " +
startNode + " to node " + endNode + " is: " + cost);
}
scanner.close();
}
}
Output
Distance Vector (Least cost routes):
From Node 0 to: 0 10 15 25 45
From Node 1 to: 10 0 5 15 25
From Node 2 to: 15 5 0 20 30
From Node 3 to: 25 15 20 0 10
From Node 4 to: 45 25 30 10 0
Enter start node: 0
Enter end node: 3
Least cost route from node 0 to node 3 is: 25
8.By using an any one Congestion Control mechanisms and
simulate the functionalities using NS
import java.util.Random;
public class TcpCongestionControl {
private static final int MAX_WINDOW_SIZE = 100; // Maximum
window size (packets)
private static final int INITIAL_CWND = 1; // Initial congestion
window size
private static final int INITIAL_SSTHRESH = 8; // Initial slow-start
threshold
private static final int PACKET_COUNT = 200; // Total number of
packets to send
private static final double LOSS_RATE = 0.05; // Simulated packet
loss rate (5%)
public static void main(String[] args) {
int cwnd = INITIAL_CWND; // Congestion window
int ssthresh = INITIAL_SSTHRESH; // Slow start threshold
int successfulPackets = 0; // Successful packets sent
int totalPacketsSent = 0; // Total packets sent
Random rand = new Random();
System.out.println("Starting TCP Congestion Control
Simulation...");
System.out.println("Initial cwnd: " + cwnd + ", ssthresh: " +
ssthresh);
while (successfulPackets < PACKET_COUNT) {
// Simulate sending packets
totalPacketsSent += cwnd;
// Simulate packet loss with a certain probability
boolean packetLost = rand.nextDouble() < LOSS_RATE;
if (packetLost) {
// Packet loss detected, perform Fast Retransmit and
Recovery
System.out.println("Packet loss detected! cwnd before
reduction: " + cwnd);
ssthresh = Math.max(cwnd / 2, 2); // Set ssthresh to half
of cwnd (minimum 2)
cwnd = 1; // Slow start again
System.out.println("New ssthresh: " + ssthresh + ", cwnd
reset to: " + cwnd);
} else {
// No packet loss, increase cwnd
if (cwnd < ssthresh) {
// Slow Start phase (exponentially increase cwnd)
cwnd *= 2;
System.out.println("Slow Start: Increased cwnd to " +
cwnd);
} else {
// Congestion Avoidance phase (linear increase of
cwnd)
cwnd += 1;
System.out.println("Congestion Avoidance: Increased
cwnd to " + cwnd);
}
}
// Ensure that the cwnd does not exceed the maximum
window size
if (cwnd > MAX_WINDOW_SIZE) {
cwnd = MAX_WINDOW_SIZE;
System.out.println("cwnd reached MAX_WINDOW_SIZE: "
+ cwnd);
}
// Count the number of successfully sent packets
successfulPackets += cwnd;
// Simulate a delay for each cycle of sending
try {
Thread.sleep(100); // Sleep for 100ms for simulation
purposes
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("\nSimulation complete!");
System.out.println("Total packets sent: " + totalPacketsSent);
System.out.println("Packets successfully delivered: " +
successfulPackets);
System.out.println("Final congestion window size: " + cwnd);
}
}
Output
Starting TCP Congestion Control Simulation...
Initial cwnd: 1, ssthresh: 8
Slow Start: Increased cwnd to 2
Slow Start: Increased cwnd to 4
Slow Start: Increased cwnd to 8
Congestion Avoidance: Increased cwnd to 9
Congestion Avoidance: Increased cwnd to 10
Packet loss detected! cwnd before reduction: 10
New ssthresh: 5, cwnd reset to: 1
Slow Start: Increased cwnd to 2
Slow Start: Increased cwnd to 4
Slow Start: Increased cwnd to 8
Congestion Avoidance: Increased cwnd to 9
...
Simulation complete!
Total packets sent: 200
Packets successfully delivered: 200
Final congestion window size: 10.
9.Examine the throughput performance of sliding window
with varying packet sizes, error rates and Round Trip Times
import java.util.Random;
public class SlidingWindowThroughput {
// Simulation parameters
private static final int MAX_WINDOW_SIZE = 10; // Maximum window
size
private static final int MAX_PACKET_SIZE = 1500; // Maximum packet
size in bytes
private static final int PACKET_COUNT = 1000; // Number of packets to
send
private static final int SIMULATION_TIME = 10000; // Simulation time
in milliseconds
// Parameters for varying conditions
private static final double[] ERROR_RATES = {0.01, 0.05, 0.1}; // Error
rates (1%, 5%, 10%)
private static final int[] RTTs = {50, 100, 200}; // RTTs in milliseconds
(50ms, 100ms, 200ms)
private static final int[] PACKET_SIZES = {500, 1000, 1500}; // Packet
sizes in bytes
public static void main(String[] args) {
// Simulate throughput with varying packet sizes, error rates, and
RTT
for (double errorRate : ERROR_RATES) {
for (int rtt : RTTs) {
for (int packetSize : PACKET_SIZES) {
System.out.println("Simulating with Packet Size: " +
packetSize + " bytes, " +
"Error Rate: " + (errorRate * 100) + "%, RTT: " + rtt + "
ms");
double throughput = simulateSlidingWindow(packetSize,
errorRate, rtt);
System.out.println("Throughput: " + throughput + " Mbps\
n");
}
}
}
}
// Simulate the Sliding Window Protocol
public static double simulateSlidingWindow(int packetSize, double
errorRate, int rtt) {
int cwnd = 1; // Initial congestion window size (number of packets)
int ssthresh = 16; // Slow start threshold
int totalPacketsSent = 0;
int totalPacketsAcknowledged = 0;
long startTime = System.currentTimeMillis();
Random rand = new Random();
while (totalPacketsSent < PACKET_COUNT) {
// Simulate sending packets based on current window size
for (int i = 0; i < cwnd; i++) {
totalPacketsSent++;
// Simulate packet error (packet loss)
if (rand.nextDouble() < errorRate) {
System.out.println("Packet " + totalPacketsSent + " lost
due to error.");
continue; // Skip to the next packet (retransmission will be
needed)
}
// Simulate the RTT delay for each packet
try {
Thread.sleep(rtt);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Acknowledge the packet
totalPacketsAcknowledged++;
}
// After a successful transmission, increase the congestion
window size
if (cwnd < ssthresh) {
cwnd *= 2; // Slow start phase: exponentially increase cwnd
} else {
cwnd += 1; // Congestion avoidance: linearly increase cwnd
}
// Ensure the window size doesn't exceed the maximum allowed
window size
if (cwnd > MAX_WINDOW_SIZE) {
cwnd = MAX_WINDOW_SIZE;
}
}
long endTime = System.currentTimeMillis();
long elapsedTime = endTime - startTime; // in milliseconds
// Calculate throughput in Mbps
double totalDataSent = totalPacketsAcknowledged * packetSize *
8; // Total data in bits
double throughput = totalDataSent / elapsedTime; // Throughput in
bits/ms
throughput *= 1000; // Convert to Mbps
return throughput;
}
}
Output
Simulating with Packet Size: 500 bytes, Error Rate: 1.0%, RTT: 50 ms
Throughput: 3.5 Mbps
Simulating with Packet Size: 500 bytes, Error Rate: 1.0%, RTT: 100 ms
Throughput: 3.2 Mbps
Simulating with Packet Size: 500 bytes, Error Rate: 1.0%, RTT: 200 ms
Throughput: 2.9 Mbps
Simulating with Packet Size: 1000 bytes, Error Rate: 1.0%, RTT: 50 ms
Throughput: 7.1 Mbps
Simulating with Packet Size: 1000 bytes, Error Rate: 5.0%, RTT: 50 ms
Throughput: 4.3 Mbps
10.Compare the performance of a network by implementing Distance
Vector Routing algorithm and link state routing