0% found this document useful (0 votes)
64 views12 pages

Prog 4 and 5

The document outlines the development of a Java program that implements the Bellman-Ford algorithm for finding the shortest path between vertices in a network, along with a client-server program using TCP/IP sockets for file transfer. The Bellman-Ford program allows users to input the number of nodes, adjacency matrix, and distances, while the client-server program facilitates sending a filename from the client to the server, which then sends back the file's contents. Additionally, it mentions the introduction of UTF-8 as the default charset in Java 18 for standard APIs.

Uploaded by

Hemanth BR
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views12 pages

Prog 4 and 5

The document outlines the development of a Java program that implements the Bellman-Ford algorithm for finding the shortest path between vertices in a network, along with a client-server program using TCP/IP sockets for file transfer. The Bellman-Ford program allows users to input the number of nodes, adjacency matrix, and distances, while the client-server program facilitates sending a filename from the client to the server, which then sends back the file's contents. Additionally, it mentions the introduction of UTF-8 as the default charset in Java 18 for standard APIs.

Uploaded by

Hemanth BR
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

1.

Develop a program to find the shortest path between vertices using the
bellman-ford and Path vector routing algorithm

(base) ksit@cnlab4:~/lab$ gedit bellman.java


Type this below code

import java.util.*; // Importing the necessary utilities from the Java library (Scanner for input, etc.)

class bellman
{ // Define the main class "Bellman" to represent the Bellman-Ford algorithm.
// Define a static nested class "Node" to represent each entry in the routing table.
// Each "Node" will have a "distance" (the shortest path) and a "phop" (the previous hop node).
public static class Node
{
int distance; // Distance to the destination node
char phop; // Previous hop node (used to trace the path)
}

public static void main(String[] args)


{
int i, j, n; // Declare variables for loop counters and number of nodes
Scanner in = new Scanner(System.in); // Create a scanner object to read input from the user
System.out.println("Enter the number of nodes"); // Ask for the number of nodes in the network
n = in.nextInt(); // Read the number of nodes from the user
// Initialize the routing table (a 2D array of Nodes) and the adjacency matrix (graph representation)
Node[][] rt = new Node[n][n]; // Routing table (n x n array of Nodes)
int[][] g = new int[n][n]; // Graph representation using adjacency matrix (n x n)

// Character array representing the node labels (a, b, c, ... for up to 12 nodes)
char[] ch = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'};

// Initialize each element in the routing table (set it to a new Node)


for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
rt[i][j] = new Node(); // Create a new Node object for each position in the routing table
}
}

// Prompt the user to enter the adjacency matrix (connections between nodes)
System.out.println("Enter the adjacency matrix:");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
g[i][j] = in.nextInt(); // Read the adjacency matrix (1 for direct connection, 0 for no connection)
}
}
// Ask the user to input the distance for each edge (between directly connected nodes)
System.out.println("Enter the distance:");
for (i = 0; i < n; i++) {
System.out.println("The distance between node " + ch[i] + " and others:");
for (j = 0; j < n; j++) {
if (g[i][j] == 1) { // If there's a direct connection between node i and node j
System.out.println("node " + ch[j] + " is:");

rt[i][j].distance = in.nextInt(); // Read the distance from the user and assign it to the routing table
} else {
rt[i][j].distance = 999; // If no direct connection, set distance to 999 (infinity)
}
rt[i][j].phop = ch[i]; // The previous hop for any node initially is itself
}
}

// Create an array to store the adjacent nodes of a given node


int[] adjacentNodes = new int[n]; // Array to hold adjacent node indices
int adc = 0, choice; // Initialize variables: adc (adjacent nodes count), choice (user menu
choice)

// Start a do-while loop to repeatedly display the menu and process user input
do {
adc = 0; // Reset the adjacent nodes count to 0 for each new iteration
System.out.println("1. Routing table information\n2. Routing table\n3. Exit"); // Display
menu options
choice = in.nextInt(); // Read the user's menu choice

// Based on the choice, execute the corresponding action


switch (choice) {
case 1: // If the user selects option 1, construct the routing table for a given node
System.out.println("Enter the node for which routing table should be constructed:");
int id = in.nextInt(); // Read the node index (1-based input)
id--; // Convert to 0-based index (since array indexing starts at 0)

System.out.println("The neighbours of " + ch[id] + " are:");

// Identify all neighboring nodes for the given node (adjacent nodes)
for (i = 0; i < n; i++) {
if (g[id][i] == 1) { // If there's a direct connection between node 'id' and node 'i'
adjacentNodes[adc++] = i; // Store the neighboring node in the adjacentNodes array
System.out.println(ch[i]); // Print the neighbor's label
}
}

// Calculate the shortest path for each destination node


for (i = 0; i < n; i++) {
if (id != i) { // Skip the current node as the shortest path to itself is always 0
int small = rt[id][i].distance; // Start with the initial distance from the routing table
int chosen = id; // Initially, assume the previous hop is the current node (itself)
// Check through each adjacent node to see if a shorter path can be found
for (j = 0; j < adc; j++) {
int total = rt[id][adjacentNodes[j]].distance + rt[adjacentNodes[j]][i].distance;
if (total < small) { // If a shorter path is found
small = total; // Update the shortest distance
chosen = adjacentNodes[j]; // Update the previous hop
rt[id][i].phop = ch[chosen]; // Update the previous hop in the routing table
}
}
rt[id][i].distance = small; // Update the distance in the routing table
System.out.println("The smallest distance from " + ch[id] + " to " + ch[i] + " is " + small);
System.out.println("The previous hop is " + rt[id][i].phop); // Print the previous hop
} else
{
rt[id][i].distance = 0; // Distance to itself is always 0
}
}
break;

case 2: // If the user selects option 2, display the entire routing table
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
System.out.print(rt[i][j].distance + "," + rt[i][j].phop + "\t"); // Print each entry in the routing table
}
System.out.println(); // New line after each row of the table
}
break;
}
} while (choice != 3); // Continue the loop until the user chooses to exit (choice 3)
}
}

OUTPUT:
(base) ksit@cnlab4:~/lab$ javac bellman.java
(base) ksit@cnlab4:~/lab$ java bellman
Enter the number of nodes
4
Enter the adjacency matrix:
0110
1001
1001
0110
Enter the distance:
The distance between node a and
node b is:
2
node c is:
6
The distance between node b and
node a is:
2
node d is:
1
The distance between node c and
node a is:
6
node d is:
2
The distance between node d and
node b is:
1
node c is:
2

1. Routing table information


2. Routing table
3. Exit
2

999,a 2,a 6,a 999,a

2,b 999,b 999,b 1,b

6,c 999,c 999,c 2,c

999,d 1,d 2,d 999,d

1. Routing table information


2. Routing table
3. Exit
1

Enter the node for which routing table should be constructed:


1
The neighbors of a are:
b
c
The smallest distance from a to b is 2
The previous hop is a
The smallest distance from a to c is 6
The previous hop is a
The smallest distance from a to d is 3
The previous hop is b

1. Routing table information


2. Routing table
3. Exit
2

0,a 2,a 6,a 3,b

2,b 999,b 999,b 1,b

6,c 999,c 999,c 2,c

999,d 1,d 2,d 999,d

1. Routing table information


2. Routing table
3. Exit
1

Enter the node for which routing table should be constructed:


2
The neighbors of b are:
a
d
The smallest distance from b to a is 2
The previous hop is b
The smallest distance from b to c is 3
The previous hop is d
The smallest distance from b to d is 1
The previous hop is b

1. Routing table information


2. Routing table
3. Exit
2

0,a 2,a 6,a 3,b

2,b 0,b 3,d 1,b

6,c 999,c 999,c 2,c


999,d 1,d 2,d 999,d

1. Routing table information


2. Routing table
3. Exit
1

Enter the node for which routing table should be constructed:


1
The neighbors of a are:
b
c
The smallest distance from a to b is 2
The previous hop is a
The smallest distance from a to c is 5
The previous hop is b
The smallest distance from a to d is 3
The previous hop is b

1. Routing table information


2. Routing table
3. Exit
2

0,a 2,a 5,b 3,b

2,b 0,b 3,d 1,b

6,c 999,c 999,c 2,c

999,d 1,d 2,d 999,d

1. Routing table information


2. Routing table
3. Exit
3
2. Using TCP/IP sockets, write a client – server program to make the client
send the file name and to make the server send back the contents of the re-
quested file if present.

(base) ksit@cnlab4:~/lab$ gedit myserver.java

SERVER SIDE PROGRAM save as myserver.java

// Import necessary libraries for network and file operations


import java.util.*; // For using List and other collections
import java.net.*; // For handling networking (ServerSocket, Socket)
import java.io.*; // For input/output operations (DataInputStream, DataOutputStream)
import java.nio.file.*; // For file-related operations (Files)
import java.nio.charset.Charset; // For handling character encoding

// Define the server class


class myserver {
public static void main(String[] args) throws Exception {
// Create a ServerSocket on port 8000 to listen for client connections
ServerSocket ss = new ServerSocket(8000);
System.out.println("Server started. Waiting for client to connect...");

// Wait and accept a client connection


Socket ns = ss.accept();
System.out.println("Client connected.");

// Set up input and output streams to communicate with the client


DataInputStream din = new DataInputStream(ns.getInputStream()); // Input stream to read
data from the client
DataOutputStream dout = new DataOutputStream(ns.getOutputStream()); // Output stream
to send data to the client

// Read the filename sent by the client


String fname = din.readUTF();
System.out.println("Filename received: " + fname);

// Set the character set encoding to UTF-8


Charset cs = Charset.forName("UTF-8");

// Read all lines of the file specified by 'fname' using the UTF-8 charset
List<String> lines = Files.readAllLines(Paths.get(fname), cs); // 'Paths.get(fname)' creates a
Path object for the filename

// Loop through each line in the file and send it to the client
for (int i = 0; i < lines.size(); i++) {
dout.writeUTF(lines.get(i)); // Write each line to the output stream
dout.flush(); // Ensure that the data is sent immediately
}

// After sending all lines, send a "stop" message to signal the end of the file transmission
dout.writeUTF("stop");
// Output a message indicating the file has been successfully sent
System.out.println("File sent successfully!");

// Close the input and output streams and the connections with the client and server
din.close(); // Close the input stream
dout.close(); // Close the output stream
ns.close(); // Close the client connection
ss.close(); // Close the server socket (this stops the server)
}
}

(base) ksit@cnlab4:~/lab$ gedit myclient.java


Client Side Program save as myclient.java

// Import necessary libraries for network and I/O operations


import java.util.*; // For using Scanner to read input from the user
import java.net.*; // For handling networking (Socket)
import java.io.*; // For input/output operations (DataInputStream, DataOutputStream)

class myclient {
public static void main(String[] args) throws Exception {
// Create a new Socket to connect to the server at localhost on port 8000
Socket cs = new Socket("localhost", 8000);

// Input stream to receive data from the server


DataInputStream din = new DataInputStream(cs.getInputStream());

// Output stream to send data to the server


DataOutputStream dout = new DataOutputStream(cs.getOutputStream());

// Create a scanner object to read user input from the console


Scanner in = new Scanner(System.in);

// Prompt the user to enter a filename to request from the server


System.out.println("Enter a filename:");

// Read the filename entered by the user


String fname = in.next();

// Print confirmation that the filename has been sent


System.out.println("File name sent: " + fname);

// Send the filename to the server


dout.writeUTF(fname);

String msg;

// Use a try-catch block to handle any exceptions, like file not existing
try {
// Read the lines sent by the server until the "stop" message is received
do {
msg = din.readUTF(); // Read a line from the server
System.out.println(msg); // Print the line to the console
} while (!msg.equals("stop")); // Continue until "stop" message is received

} catch (Exception e) {
// If an exception occurs (e.g., file doesn't exist), print this message
System.out.println("File doesn't exist");
} finally {
// Close the input stream and the socket connection, regardless of whether an exception
occurs
din.close();
cs.close();
}
}
}

Create another editor and create new file


#gedit hello.txt file
Type any text like sample given below
hi
hello
how are you
thank you
stop // always file end with stop key word
save the file

RUN THE PROGRAM


Always first compile and run the server program
(base) ksit@cnlab4:~/lab$ javac myserver.java
(base) ksit@cnlab4:~/lab$ java myserver
Open the new editor
RUN the client side program
(base) ksit@cnlab4:~/lab$ javac myclient.java
(base) ksit@cnlab4:~/lab$ java myclient
Enter the file name: hello.txt

SERVER SIDE OUTPUT


(base) ksit@cnlab4:~/lab$ javac myserver.java
(base) ksit@cnlab4:~/lab$ java myserver
Filename received : hello.txt
file sent successfully!!
(base) ksit@cnlab4:~/lab$

CLIENT SIDE OUTPUT


(base) ksit@cnlab4:~/lab$ javac myclient.java
(base) ksit@cnlab4:~/lab$ java myclient
Enter the file name: hello.txt
hi
hello
how are you
thank you
stop

Java Platform Enhancement Proposal (JEP) 400 introduced UTF-8(UTF-8 stands for Unicode
Transformation Format-8. It's a character encoding system that's used to represent characters in
electronic communication.) as the default charset for standard Java APIs across all operating sys-
tems, starting with Java 18, except for the console input and output encoding. In IBM Semeru
Runtime Certified Edition for z/OS 21 (Semeru 21), UTF-8 is the default value of the file.

A socket is a connection point that allows data to be sent or received between two devices on a net-
work. It's made up of an IP address and a port number.
How sockets work
• Sockets allow different processes to communicate over a network.
• They enable applications and devices to exchange data over a network, such as the internet or
a local network.
• Sockets are often used for client and server interaction.
Different types of sockets
• Stream sockets: Allow processes to communicate using TCP.
• Datagram sockets: Allow processes to communicate using UDP.
• Raw sockets: Allow access to ICMP. They can be used to transport serial data through an IP
network.
Socket use cases
• Datagram sockets are commonly used in real-time applications like streaming audio or video.
• Raw sockets are used for building transport-layer protocols that aren't natively supported by
the kernel. They're also used for routing protocols like OSPF and ICMP.
Socket classes
• Socket classes are used to represent the connection between a server program and a client
program.

There are 65,535 possible port numbers in networking, but not all are in common use. Port numbers
are used to identify applications and services on a network.
Port number ranges
• Well-known ports: Range from 0 to 1023 and are assigned to services
• Registered ports: Range from 1024 to 49,151
• Dynamic/private ports: Range from 49,152 to 65,535
Commonly used ports
• Port 80: Hypertext Transfer Protocol (HTTP)
• Port 123: Network Time Protocol (NTP)
• Port 179: Border Gateway Protocol (BGP)
• Port 443: HTTP Secure (HTTPS)
• Port 500: Internet Security Association and Key Management Protocol (ISAKMP)
• Port 3389: Remote Desktop Protocol (RDP)
• Port 20 and 21: FTP
• Port 22: Secure Shell
• Port 53: Domain name system (DNS)
The Java DataInputStream readUTF() method reads in a string that has been encoded using a
modified UTF-8 format. The string of character is decoded from the UTF and returned as String.

You might also like