0% found this document useful (0 votes)
51 views16 pages

Shortest Path Algorithms in Java

The document outlines the implementation of a Java program to find the shortest path between vertices using the Bellman-Ford algorithm and a client-server model for file transfer. It includes detailed code for both the server and client applications, demonstrating how to send a filename from the client to the server and receive the file's contents. Additionally, it mentions the introduction of UTF-8 as the default charset for Java APIs starting with Java 18.

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

Topics covered

  • Socket classes,
  • Bellman-Ford algorithm,
  • Secure Shell,
  • Java exceptions,
  • Character encoding,
  • Adjacency matrix,
  • Port numbers,
  • Network Time Protocol,
  • Java APIs,
  • Input/output operations
0% found this document useful (0 votes)
51 views16 pages

Shortest Path Algorithms in Java

The document outlines the implementation of a Java program to find the shortest path between vertices using the Bellman-Ford algorithm and a client-server model for file transfer. It includes detailed code for both the server and client applications, demonstrating how to send a filename from the client to the server and receive the file's contents. Additionally, it mentions the introduction of UTF-8 as the default charset for Java APIs starting with Java 18.

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

Topics covered

  • Socket classes,
  • Bellman-Ford algorithm,
  • Secure Shell,
  • Java exceptions,
  • Character encoding,
  • Adjacency matrix,
  • Port numbers,
  • Network Time Protocol,
  • Java APIs,
  • Input/output operations

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 [Link]


Type this below code

import [Link].*; // 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([Link]); // Create a scanner object to read input from the user
[Link]("Enter the number of nodes"); // Ask for the number of nodes in the network
n = [Link](); // 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)
[Link]("Enter the adjacency matrix:");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
g[i][j] = [Link](); // 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)
[Link]("Enter the distance:");
for (i = 0; i < n; i++) {
[Link]("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
[Link]("node " + ch[j] + " is:");

rt[i][j].distance = [Link](); // 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
[Link]("1. Routing table information\n2. Routing table\n3. Exit"); // Display
menu options
choice = [Link](); // 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
[Link]("Enter the node for which routing table should be constructed:");
int id = [Link](); // Read the node index (1-based input)
id--; // Convert to 0-based index (since array indexing starts at 0)

[Link]("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
[Link](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
[Link]("The smallest distance from " + ch[id] + " to " + ch[i] + " is " + small);
[Link]("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++)
{
[Link](rt[i][j].distance + "," + rt[i][j].phop + "\t"); // Print each entry in the routing table
}
[Link](); // 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 [Link]
(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
requested file if present.

(base) ksit@cnlab4:~/lab$ gedit [Link]

SERVER SIDE PROGRAM save as [Link]

// Import necessary libraries for network and file operations


import [Link].*; // For using List and other collections
import [Link].*; // For handling networking (ServerSocket, Socket)
import [Link].*; // For input/output operations (DataInputStream, DataOutputStream)
import [Link].*; // For file-related operations (Files)
import [Link]; // 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);
[Link]("Server started. Waiting for client to connect...");

// Wait and accept a client connection


Socket ns = [Link]();
[Link]("Client connected.");

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


DataInputStream din = new DataInputStream([Link]()); // Input stream to read
data from the client
DataOutputStream dout = new DataOutputStream([Link]()); // Output stream
to send data to the client

// Read the filename sent by the client


String fname = [Link]();
[Link]("Filename received: " + fname);

// Set the character set encoding to UTF-8


Charset cs = [Link]("UTF-8");

// Read all lines of the file specified by 'fname' using the UTF-8 charset
List<String> lines = [Link]([Link](fname), cs); // '[Link](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 < [Link](); i++) {
[Link]([Link](i)); // Write each line to the output stream
[Link](); // Ensure that the data is sent immediately
}

// After sending all lines, send a "stop" message to signal the end of the file transmission
[Link]("stop");

// Output a message indicating the file has been successfully sent


[Link]("File sent successfully!");

// Close the input and output streams and the connections with the client and server
[Link](); // Close the input stream
[Link](); // Close the output stream
[Link](); // Close the client connection
[Link](); // Close the server socket (this stops the server)
}
}

(base) ksit@cnlab4:~/lab$ gedit [Link]


Client Side Program save as [Link]

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


import [Link].*; // For using Scanner to read input from the user
import [Link].*; // For handling networking (Socket)
import [Link].*; // 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([Link]());

// Output stream to send data to the server


DataOutputStream dout = new DataOutputStream([Link]());

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


Scanner in = new Scanner([Link]);

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


[Link]("Enter a filename:");

// Read the filename entered by the user


String fname = [Link]();

// Print confirmation that the filename has been sent


[Link]("File name sent: " + fname);

// Send the filename to the server


[Link](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 = [Link](); // Read a line from the server
[Link](msg); // Print the line to the console
} while (![Link]("stop")); // Continue until "stop" message is received

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

Create another editor and create new file


#gedit [Link] 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 [Link]
(base) ksit@cnlab4:~/lab$ java myserver
Open the new editor
RUN the client side program
(base) ksit@cnlab4:~/lab$ javac [Link]
(base) ksit@cnlab4:~/lab$ java myclient
Enter the file name: [Link]

SERVER SIDE OUTPUT


(base) ksit@cnlab4:~/lab$ javac [Link]
(base) ksit@cnlab4:~/lab$ java myserver
Filename received : [Link]
file sent successfully!!
(base) ksit@cnlab4:~/lab$

CLIENT SIDE OUTPUT


(base) ksit@cnlab4:~/lab$ javac [Link]
(base) ksit@cnlab4:~/lab$ java myclient
Enter the file name: [Link]
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
systems, 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
network. 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.

3. Develop a program on a datagram socket for client/server to


display the messages on client side, typed at the server side.
Server side Program
import [Link].*; // Importing necessary networking classes
import [Link].*; // Importing utility classes for Scanner
class MyServer {
public static void main(String args[]) throws Exception
{ // Creating a DatagramSocket to listen on port 15000
DatagramSocket ds = new DatagramSocket(15000);
// Creating a buffer to store received data (100 bytes)
byte[] buffer = new byte[100];
// Creating a Scanner object to take server input
Scanner in = new Scanner([Link]);
// Variable to store server response
String str2;
do {
// Creating a DatagramPacket to receive data
DatagramPacket p = new DatagramPacket(buffer, [Link]);
// Receiving data from the client
[Link](p);
// Converting received bytes into a string and trimming extra spaces
String str = new String([Link](), 0, [Link]());
// Printing client's message
[Link]("Client says: " + str);
// Asking for server response
[Link]("Server says: ");
str2 = [Link](); // Taking user input
// Clearing the buffer before sending a new message
[Link](buffer, (byte) 0);
// Converting user input (str2) into bytes and storing it in the buffer
for (int i = 0; i < [Link](); i++)
buffer[i] = (byte) [Link](i);

// Sending response back to the client on port 16000


[Link](new DatagramPacket(buffer, [Link], [Link](), 16000));
} while (![Link]("bye")); // Exit the loop if server types "bye"

// Indicating chat is closing


[Link]("Closing chat application");
// Closing the DatagramSocket
[Link]();
}
}

Client:
import [Link].*; // Importing Java networking package for UDP communication
import [Link].*; // Importing utility package for Scanner class (used for user input)

class MyClient {
public static void main(String args[]) throws Exception {
// Creating a DatagramSocket to send and receive data on port 16000
DatagramSocket ds = new DatagramSocket(16000);
// Creating a buffer (byte array) to store sent and received data (100 bytes capacity)
byte[] buffer = new byte[100];
// Creating a Scanner object to take user input from the console
Scanner in = new Scanner([Link]);
// Displaying welcome message to the user
[Link]("Chat Application Started!... Type a message to send and 'bye' to quit");
// Declaring strings to store messages: 'str' for receiving, 'str2' for sending
String str = "", str2;
do {
// Prompting the user to enter a message
[Link]("Client says: ");

// Reading the user input message


str2 = [Link]();
// Clearing the buffer before storing new message
[Link](buffer, (byte) 0);
// Converting user input (str2) into bytes and storing it in the buffer
for (int i = 0; i < [Link](); i++)
buffer[i] = (byte) [Link](i);
// Sending the message to the server on port 15000
[Link](new DatagramPacket(buffer, [Link], [Link](), 15000));
// If the message is not "bye", receive the response from the server
if (![Link]("bye")) {
[Link]("Server says: ");
// Creating a DatagramPacket to receive the server's response
DatagramPacket p = new DatagramPacket(buffer, [Link]);
// Receiving data from the server
[Link](p);
// Extracting received message from the buffer (avoiding extra unwanted characters)
str = new String([Link](), 0, [Link]());
// Printing the server's response
[Link](str);
}
} while (![Link]("bye")); // Continue chat until the client types "bye"
// Displaying exit message when the chat is closed
[Link]("Closing chat application");
// Closing the DatagramSocket to release resources
[Link]();
}
}

OUTPUT:
Peer1:
(base) ksit@cnlab4:~/lab$ javac [Link]
(base) ksit@cnlab4:~/lab$ java MyServer
client says: hi
Server says:hello
client says: how are you
Server says:fine thank you
client says: bye
Server says:bye
Closing chat application
(base) ksit@cnlab4:~/lab$
Peer2:
(base) ksit@cnlab4:~/lab$ javac [Link]
(base) ksit@cnlab4:~/lab$ java MyClient
Chat Application Started!... Type message to send and bye to quit
client says: hi
Server says:hello
client says: how are you
Server says:fine thank you
client says: bye
Closing chat application
(base) ksit@cnlab4:~/lab$

You might also like