ASSIGNMENT
Name : D.K.Karthik Varma
Roll no : 421132
1) Construct a TCP client-server system to allow client programs to get the system date and time from
the server. When a client connects to the server, the server gets the local time on the machine and
sends it to the client. The client displays the date and time on the screen and terminates.
Server1.java
import java.io.*;
import
java.net.*;
import
java.text.SimpleDateFormat;
import java.util.Date;
public class Server1 {
public static void main(String[] args) {
try {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("Server is running and waiting for
connections...");
while (true) {
// Wait for a client connection
Socket clientSocket = serverSocket.accept();
System.out.println("Connection from: " +
clientSocket);
// Get the current date and time
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd
HH:mm:ss");
Date currentDate = new Date();
String currentTime = dateFormat.format(currentDate);
// Send the current time to the client
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true); out.println(currentTime);
// Close the
connection
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client1.java
import java.io.*;
import
java.net.*;
public class Client1 {
public static void main(String[] args) {
try {
// Create a socket to connect to the server
Socket socket = new Socket("localhost",
9999);
// Receive the date and time from the server
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()))
; String currentTime = in.readLine();
System.out.println("Received date and time from server: " + currentTime);
// Close the connection
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2) Construct client-server programming: The client has a list of words (at least 20 words) and the
server has a dictionary (at least 15 entries). The client picks up a random word from its list and sends it
to the server. The server responds with its meaning, if found else adds this entry to its dictionary with
its meaning.
Server2.java
import java.io.*;
import java.net.*;
import java.util.*;
public class Server {
private static Map<String, String> dictionary = new HashMap<>();
static {
// Initialize dictionary with some entries
dictionary.put("apple", "a fruit");
dictionary.put("banana", "an elongated curved
fruit");
dictionary.put("carrot", "a long pointed orange vegetable");
}
public static void main(String[] args) {
try {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("Server is running and waiting for
connections...");
while (true) {
// Wait for a client connection
Socket clientSocket = serverSocket.accept();
System.out.println("Connection from: " +
clientSocket);
// Handle client request
handleClientRequest(clientSocket);
// Close the
connection
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void handleClientRequest(Socket clientSocket) throws IOException {
// Receive word from client
BufferedReader in = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()))
;
String word = in.readLine();
// Look up the meaning in the dictionary
String meaning = dictionary.get(word);
// If meaning not found, add to dictionary
if (meaning == null) {
meaning = "Meaning not found";
addToDictionary(word,
meaning);
}
// Send meaning to client
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true); out.println(meaning);
}
private static void addToDictionary(String word, String meaning)
{ dictionary.put(word, meaning);
System.out.println("Added new word to dictionary: " + word + " - " + meaning);
}
}
Client2.java
import java.io.*;
import java.net.*;
import java.util.*;
public class Client {
private static final List<String> wordList = Arrays.asList(
"apple", "banana", "carrot", "dog", "cat", "house", "tree", "book", "computer",
"table", "chair", "phone", "pen", "paper", "lamp", "flower", "river", "mountain",
"sky", "sun"
);
public static void main(String[] args) {
try {
// Create a socket to connect to the server
Socket socket = new Socket("localhost",
9999);
// Select a random word from the list
Random random = new Random();
String randomWord = wordList.get(random.nextInt(wordList.size()));
// Send the random word to the server
PrintWriter out = new PrintWriter(socket.getOutputStream(),
true); out.println(randomWord);
// Receive the meaning from the server
BufferedReader in = new
BufferedReader(new
InputStreamReader(socket.getInputStream()))
; String meaning = in.readLine();
System.out.println("Meaning of '" + randomWord + "': " + meaning);
// Close the connection
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3) Construct a Java program using client-server socket programming: The client will enter an integer
number and the server will return its factorial.
Server3.java
import java.io.*;
import
java.net.*;
public class Server3 {
public static void main(String[] args) {
try {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("Server is running and waiting for
connections...");
while (true) {
// Wait for a client connection
Socket clientSocket = serverSocket.accept();
System.out.println("Connection from: " +
clientSocket);
// Handle client request
handleClientRequest(clientSocket);
// Close the
connection
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void handleClientRequest(Socket clientSocket) throws IOException {
// Receive the integer number from the client
BufferedReader in = new
BufferedReader(new
InputStreamReader(clientSocket.getInputStream()))
; int number = Integer.parseInt(in.readLine());
// Calculate factorial
int factorial = calculateFactorial(number);
// Send factorial to the client
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true); out.println(factorial);
}
private static int calculateFactorial(int n) {
if (n == 0)
return
1; else
return n * calculateFactorial(n - 1);
}
}
Client3.java
import java.io.*;
import
java.net.*;
import java.util.Scanner;
public class Client3 {
public static void main(String[] args) {
try {
// Create a socket to connect to the server
Socket socket = new Socket("localhost", 9999);
Scanner scanner = new Scanner(System.in);
// Get the integer number from the user
System.out.print("Enter an integer number:
"); int number = scanner.nextInt();
// Send the number to the server
PrintWriter out = new PrintWriter(socket.getOutputStream(),
true); out.println(number);
// Receive factorial from the server
BufferedReader in = new
BufferedReader(new
InputStreamReader(socket.getInputStream()));
int factorial = Integer.parseInt(in.readLine());
System.out.println("Factorial of " + number + ": " + factorial);
// Close the connection
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
4. )
Server4.java
import java.io.*;
import
java.net.*;
public class Server4 {
public static void main(String[] args) {
try {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("Server is running and waiting for
connections...");
while (true) {
// Wait for a client connection
Socket clientSocket = serverSocket.accept();
System.out.println("Connection from: " +
clientSocket);
// Handle client request
handleClientRequest(clientSocket);
// Close the
connection
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void handleClientRequest(Socket clientSocket) throws IOException {
// Receive the mark from the client
BufferedReader in = new
BufferedReader(new
InputStreamReader(clientSocket.getInputStream()))
; int mark = Integer.parseInt(in.readLine());
// Calculate grade
String grade = calculateGrade(mark);
// Send grade to the client
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true); out.println(grade);
}
private static String calculateGrade(int mark) {
if (mark >= 85 && mark <= 100)
return "Grade A";
else if (mark >= 70 && mark <= 84)
return "Grade B";
else if (mark >= 60 && mark <= 69)
return "Grade C";
else if (mark >= 50 && mark <= 59)
return "Grade D";
else
return "Fail";
}
}
Client4.java
import java.io.*;
import
java.net.*;
import java.util.Scanner;
public class Client4 {
public static void main(String[] args) {
try {
// Create a socket to connect to the server
Socket socket = new Socket("localhost", 9999);
Scanner scanner = new Scanner(System.in);
// Get the mark from the user
System.out.print("Enter the mark: ");
int mark = scanner.nextInt();
// Send the mark to the server
PrintWriter out = new PrintWriter(socket.getOutputStream(),
true); out.println(mark);
// Receive grade from the server
BufferedReader in = new
BufferedReader(new
InputStreamReader(socket.getInputStream()))
; String grade = in.readLine();
System.out.println("Grade: " + grade);
// Close the connection
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
5) Construct a Java program using client-server socket programming: A client enters 0, 1, 2, 3, and 4 in
sequence and the server returns the results 3, 3, 7, 15, and 27 respectively in sequence. (One by one)
Server5.java
import java.io.*;
import
java.net.*;
public class Server5 {
public static void main(String[] args) {
try {
// Create a server socket
ServeConstruct a Java program using client-server programming: The client sends
a word and a number to the server and the server sends the letter which
occurs the given number of times in the given word, if it exists else send the
letter which occurs at maximum number of times in the given word.
Connection should not terminate till the client wants torSocket serverSocket =
new ServerSocket(9999);
System.out.println("Server is running and waiting for connections...");
while (true) {
// Wait for a client connection
Socket clientSocket = serverSocket.accept();
System.out.println("Connection from: " +
clientSocket);
// Handle client request
handleClientRequest(clientSocket);
// Close the
connection
clientSocket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void handleClientRequest(Socket clientSocket) throws IOException {
// Receive the number from the client
BufferedReader in = new
BufferedReader(new
InputStreamReader(clientSocket.getInputStream()))
; int number = Integer.parseInt(in.readLine());
// Calculate result based on the received number
int result = calculateResult(number);
// Send result to the client
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
true); out.println(result);
}
private static int calculateResult(int number) {
// Perform calculation based on the given sequence
switch (number) {
case 0:
return 3;
case Construct a Java program using client-server programming: The client sends
a word and a number to the server and the server sends the letter which
occurs the given number of times in the given word, if it exists else send the
letter which occurs at maximum number of times in the given word.
Connection should not terminate till the client wants to1:
return 3;
case 2:
return 7;
case 3:
return 15;
case 4:
return
27; default:
return -1; // Invalid input
}
}
}
Client5.java
import java.io.*;
import
java.net.*;
public class Client5 {
public static void main(String[] args) {
try {
// Create a socket to connect to the server
Socket socket = new Socket("localhost",
9999);
// Create a PrintWriter to send numbers to the server
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
// Send numbers 0, 1, 2, 3, and 4 in sequence
for (int i = 0; i < 5; i++) {
out.println(i);
// Receive the result from the server
BufferedReader in = new
BufferedReader(new
InputStreamReader(socket.getInputStream()));
int result = Integer.parseInt(in.readLine());
System.out.println("Result for " + i + ": " + result);
}
// Close the connection
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
6) Construct a Java program using client-server programming: The client sends a word and a number
to the server and the server sends the letter which occurs the given number of times in the given word,
if it exists else send the letter which occurs at maximum number of times in the given word.
Connection should not terminate till the client wants to.
Server6.java
import java.io.*;
import java.net.*;
import java.util.*;
public class Server {
public static void main(String[] args) {
try {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("Server is running and waiting for
connections...");
while (true) {
// Wait for a client connection
Socket clientSocket = serverSocket.accept();
System.out.println("Connection from: " +
clientSocket);
// Handle client request
handleClientRequest(clientSocket);
// Close the connection
// clientSocket.close(); // Keep the connection
terminate open until the client wants to
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static void handleClientRequest(Socket clientSocket) throws IOException {
BufferedReader in = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
while (true) {
// Receive word and number from the client
String word = in.readLine();
int number = Integer.parseInt(in.readLine());
// Find the letter occurrence based on the client's
request char result = findLetterOccurrence(word,
number);
// Send the result to the client
out.println(result);
// Check if the client wants to terminate the connection
String terminate = in.readLine();
if (terminate.equals("quit")) {
break; // Exit the loop if the client wants to quit
}
}
}
private static char findLetterOccurrence(String word, int number)
{ Map<Character, Integer> frequencyMap = new
HashMap<>(); for (char c : word.toCharArray()) {
frequencyMap.put(c, frequencyMap.getOrDefault(c, 0) + 1);
}
char result = '\0';
int maxFrequency = 0;
for (Map.Entry<Character, Integer> entry : frequencyMap.entrySet())
{ if (entry.getValue() == number) {
result =
entry.getKey(); break;
}
if (entry.getValue() > maxFrequency)
{ maxFrequency =
entry.getValue(); result =
entry.getKey();
}
}
return result;
}
}
Client6.java
import java.io.*;
import
java.net.*;
import java.util.Scanner;
public class Client6 {
public static void main(String[] args) {
try {
// Create a socket to connect to the server
Socket socket = new Socket("localhost", 9999);
Scanner scanner = new Scanner(System.in);
while (true) {
// Get input from the user
System.out.print("Enter a word: ");
String word = scanner.nextLine();
System.out.print("Enter a number: ");
int number = scanner.nextInt();
// Send word and number to the server
PrintWriter out = new PrintWriter(socket.getOutputStream(),
true); out.println(word);
out.println(number);
// Receive result from the server
BufferedReader in = new
BufferedReader(new
InputStreamReader(socket.getInputStream()));
char result = in.readLine().charAt(0);
System.out.println("Result: " +
result);
// Check if the user wants to terminate the connection
System.out.print("Do you want to quit? (yes/no): ");
scanner.nextLine(); // Consume newline character
String response = scanner.nextLine();
if (response.equalsIgnoreCase("yes")) {
out.println("quit"); // Tell the server to terminate the connection
break; // Exit the loop
}
}
// Close the connection
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
7)
Construct a Java UDP Client-Server Program to check if a Given String is Palindrome or no
UDPServer.java
import java.net.*;
public class UDPServer {
public static void main(String[] args) {
final int PORT = 9999;
try {
// Create a DatagramSocket to listen for client requests
DatagramSocket serverSocket = new
DatagramSocket(PORT);
System.out.println("Server is running and waiting for requests...");
while (true) {
// Create a byte array to store incoming data
byte[] receiveData = new byte[1024];
// Create a DatagramPacket to receive data from the client
DatagramPacket receivePacket = new
DatagramPacket(receiveData,
receiveData.length);
// Receive data from the client
serverSocket.receive(receivePacket);
// Extract the message from the received packet
String message = new String(receivePacket.getData(), 0,
receivePacket.getLength());
// Check if the message is a palindrome
String response = isPalindrome(message) ? "Yes, it is a palindrome." : "No, it
is not a palindrome.";
// Get the client's address and port from the received
packet InetAddress clientAddress =
receivePacket.getAddress(); int clientPort =
receivePacket.getPort();
// Create a byte array to store the response
message byte[] responseData =
response.getBytes();
// Create a DatagramPacket to send the response to the client
DatagramPacket sendPacket = new
DatagramPacket(responseData,
responseData.length, clientAddress, clientPort);
// Send the response to the client
serverSocket.send(sendPacket);
System.out.println("Response sent to " + clientAddress + ":" + clientPort);
}
} catch (Exception e) {
e.printStackTrace()
;
}
}
// Function to check if a string is a palindrome
private static boolean isPalindrome(String str)
{
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right))
{ return false;
}
left++;
right--
;
}
return true;
}
}
UDPClient.java
import java.net.*;
public class UDPClient {
public static void main(String[] args) {
final String SERVER_ADDRESS =
"localhost"; final int SERVER_PORT = 9999;
try {
// Create a DatagramSocket
DatagramSocket clientSocket = new DatagramSocket();
// Input string to check if it's a
palindrome String inputString = "radar";
// Convert the input string to bytes
byte[] sendData = inputString.getBytes();
// Create a DatagramPacket to send data to the server
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
InetAddress.getByName(SERVER_ADDRESS), SERVER_PORT);
// Send the packet to the server
clientSocket.send(sendPacket);
// Create a byte array to receive data from the server
byte[] receiveData = new byte[1024];
// Create a DatagramPacket to receive data from the server
DatagramPacket receivePacket = new
DatagramPacket(receiveData,
receiveData.length);
// Receive data from the server
clientSocket.receive(receivePacket);
// Convert the received data to a string
String response = new String(receivePacket.getData(), 0,
receivePacket.getLength());
// Print the response from the server
System.out.println("Server response: " +
response);
// Close the socket
clientSocket.close();
} catch (Exception e) {
e.printStackTrace()
;
}
}
}