0% found this document useful (0 votes)
48 views74 pages

Ritesh Socket

This document is a practical file for a Software Lab course at Maharshi Dayanand University, detailing various UNIX commands and Java socket programming assignments. It includes an index of commands related to directory management, file operations, and general-purpose commands, as well as multiple Java programming tasks involving client-server communication. The document serves as a guide for students to complete their practical assignments for the 2023-2025 academic session.

Uploaded by

Ritesh
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)
48 views74 pages

Ritesh Socket

This document is a practical file for a Software Lab course at Maharshi Dayanand University, detailing various UNIX commands and Java socket programming assignments. It includes an index of commands related to directory management, file operations, and general-purpose commands, as well as multiple Java programming tasks involving client-server communication. The document serves as a guide for students to complete their practical assignments for the 2023-2025 academic session.

Uploaded by

Ritesh
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

MAHARSHI DAYANAND UNIVERSITY

ROHTAK, HARYANA (124001)

Department of Computer Science & Applications

PRACTICAL FILE BASED ON


SOFTWARE LAB 2: 21MCA23CL2
(PAPER CODE : 21MCA23DB1)
(Session : 2023-2025)

Submitted By Submitted To
Ritesh Dr. Priti Sharma
MCA , 3rd sem
Roll: 23121
INDEX
UNIX

Sr. No. 1. Direction Oriented Commands Page No. Remarks


.

1. Ls 1

2. Mkdir 2

3. Rmdir 2

4. Cd 3

5. Pwd 4

2. File Oriented Commands

6. Cat 5

7. Cp 6

8. Rm 7
9. Mv 8

10. Wc 8

11. File 9

12. Cmp 9

13. Chmode 10

14. Touch 10

15. Tac 11

16. Tail 11

17. Head 12

3. General Purpose Commands

13
18. Date
19. Who 13

14
20. Man

21. Cal 14

22. Tee 15

SOCKET PROGRAMMING

1. WAP in java socket programming where 16 to 18


client send a text message and server
receive and print it.

2. WAP in java socket programming where 19,20


client send text message and received by
server using read and write on both sides.

3. WAP in java socket programming to check 21 to 23


the given number is prime or not.
4. WAP in java socket programming to check
the given number is Armstrong or not. 24 to 26

5. WAP in java socket programming to check


the given number is palindrome or not. 27 to 29

6. WAP in java socket programming to check


the given number is even or odd. 30 to 32

7. WAP in java socket programming to find


out the factorial of a number using bind() 33 to 36
function.

8. WAP in java socket programming to find out


the Fibonacci series. 37 to 39

9. WAP in java socket programming to find 40 to 42


out the largest among three numbers
using if else

10. WAP to illustrate client side program of 43 to 44


simple calculator using TCP.
11. WAP to illustrate server side program of
simple calculator using TCP. 45,46

12. WAP to illustrate client side program


of simple calculator using UDP. 47,48

13. WAP to illustrate server side program of


simple calculator using UDP. 49,50

14. WAP in java socket programming for client 51


application in RMI.

15. WAP in java socket programming for server 52,53


application in RMI.

16. WAP to retrieve date and time using UDP. 54 to 56

17. WAP to retrieve date and time using TCP. 57 to 59

18. Program for connection-oriented Iterative


Service in which server reverses the string 60 to 62
sent by the client and sends it back.
19. Program for connection-oriented Iterative
service in which server changes the case of 63 to 65
the strings sent by the client and sends
back (Case Server).

20. WAP in java socket programming to


demonstrate working of URL.. 66,67
UNIX

1. Direction Oriented Commands:

1) ls :
Command: ls

Used for: It lists directory contents of files and directories

OUTPUT:-

Command: ls -1

Used for: Display One File per Lines

OUTPUT:-

1
2) mkdir :
Command: mkdir directory_name

Used for: to create directories

OUTPUT:-

3) rmdir :

Command: rmdir directory_name

Used for: to remove empty directories from the file system

OUTPUT:-

2
4) cd :

Command: cd directory

Used for: To change the current working directory

OUTPUT:-

Command: cd ..

Used for: To switch one level up from the current directory

OUTPUT:-

3
5) pwd :

Command: pwd

Used for: It prints the path of the working directory

Output::-

4
2. File Oriented Commands:

6) cat :
Command: cat filename

Used for: It reads data from the file and gives their content as output

Output:-

Command: cat -n filename

Used for: It reads data from the file and gives their content as output

Output:-

5
Command: cat > filename

Used for: Create a file and enter text in it in the terminal.

Output:-

7) cp :

Command: cp source destination_directory

Used for: To copy files or group of files or directory

Output:-

6
8) rm :

Command: rm filename

Used for: to remove files

Output:-

Before rm command

Output:-

After rm command

7
9) mv :
Command: mv source destination_directory

Used for: To move files or group of files or directory

Output:-

10) wc :
Used for:used to count word, alphabet and lines.

Output:-

8
11) file :
Command: file [option] [filename]

Used for:used to determine the type of a file.

Output :-

12) cmp :
Command: cmp [OPTION]... FILE1 [FILE2 [SKIP1 [SKIP2]]]

Used for: comparison between two files.

Output :-

9
13) chmode :
Command: $ chmod +w file.txt

$ chmod +r file.txt

$ chmod +x file.txt

Used for: used to manipulate files in the UNIX environment.

Output :-

14) touch :

Command: touch filename

Used for: To create a file without any content

Output :-

10
15) tac :
Command: tac filename

Used for: to display the file content in reverse order

Output:_

16) tail :
Command: tail filename

Used for: to prints the last lines of one or more files to


standard output.By default, it shows the last 10 lines

Output:

Command: tail -n [number] filename


Used for: To change the number of lines in the output.

Output:

11
17) head :
Command: head filename

Used for: to prints the first lines of one or more files to standard
Output

Output :-

By default, it shows the first 10 lines

Command: head -n [number] filename


Used for: To change the number of lines in the output.

Output:

12
3. General Purpose Commands:

18) date :
Command: date

Used for: To show the current system time and date

Output:-

19) who :
Command: who

Used for: Show each user currently logged in to the system

Output:-

13
20) man :
Command: man ls

Used for: to display the user manual of any command that we can run on the
Terminal

Output:-

21) cal :
Command: cal

Used for: Shows current month calendar on the terminal with the current date
highlighted.

Output:-

14
22) tee :

Command: tee [OPTION]... [FILE]...

Used to: reads the standard input and writes it


to both the standard output and one ‘
or more files.
Output:-

15
1) WAP in java socket programming where client send a text message and
server receive and print it.

Server.java:-

import java.io.*;
import java.net.*;

public class SimpleServer {


public static void main(String[] args) {
int port = 65432;
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("Server listening on port " + port);
while (true) {
try {
// Accept a new client connection
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket.getInetAddress());

// Handle the client in a new thread


new Thread(() -> handleClient(clientSocket)).start();
} catch (IOException e) {
System.err.println("Error accepting client connection: " + e.getMessage());
}
}
} catch (IOException e) {
System.err.println("Could not start server: " + e.getMessage());
}
}

private static void handleClient(Socket clientSocket) {


try (BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.get
InputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {

// Read message from client


String message = in.readLine();
System.out.println("Received from client: " + message);

// Send response back to client


String response = "Message received!";
out.println(response);

16
} catch (IOException e) {
System.err.println("Error handling client: " + e.getMessage());
} finally {
try {
clientSocket.close();
} catch (IOException e) {
System.err.println("Error closing client socket: " + e.getMessage());

}
}
}
}

Output:-

17
Client.java:-

import java.io.*;
import java.net.*;

public class SimpleClient {


public static void main(String[] args) {
String host = "127.0.0.1";
int port = 65432;

try (Socket socket = new Socket(host, port);


PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()))) {

// Send message to the server


String message = "Hello, Server!";
out.println(message);
System.out.println("Sent to server: " + message);

// Receive response from the server


String response = in.readLine();
System.out.println("Received from server: " + response);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Output:-

18
2) WAP in java socket programming where client send text message
and received by server using read and write on both sides.

Server.java:-
import java.io.*;
import java.net.*;

public class Server {


public static void main(String[] args) {
try {
// Start the server and listen on port 12345
ServerSocket serverSocket = new ServerSocket(12345);
System.out.println("Server is running... Waiting for clients.");

// Accept the client connection


Socket socket = serverSocket.accept();
System.out.println("Client connected.");
// Create input and output streams
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

// Read message from client


String clientMessage = in.readLine();
System.out.println("Client says: " + clientMessage);

// Send acknowledgment to client


out.println("Message received: " + clientMessage);

// Close resources
in.close();
out.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Output:-

19
Client.java:-

import java.io.*;
import java.net.*;

public class Client {


public static void main(String[] args) {
try {
// Connect to the server at localhost and port 12345
Socket socket = new Socket("localhost", 12345);
System.out.println("Connected to the server.");

// Create input and output streams


BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

// Send a message to the server


String messageToSend = "Hello, Server!";
out.println(messageToSend);
System.out.println("Message sent to server: " + messageToSend);

// Read the server's response


String serverResponse = in.readLine();
System.out.println("Server says: " + serverResponse);

// Close resources
in.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Output:-

20
3) WAP in java socket programming to check the given number is
prime or not.
Server.java:-

import java.io.*;
import java.net.*;

public class Server {


private ServerSocket serverSocket = null;

public Server(int port) {


try {
serverSocket = new ServerSocket(port);
System.out.println("Server started and waiting for clients...");

while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket.getInetAddress());

// Handle client in a separate thread or directly


new Thread(new ClientHandler(clientSocket)).start();
}
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}

public static void main(String[] args) {


Server server = new Server(5000);
}
}

class ClientHandler implements Runnable {


private Socket clientSocket;

public ClientHandler(Socket socket) {


this.clientSocket = socket;
}

public void run() {


try (DataInputStream in = new DataInputStream(clientSocket.getInputStream())) {
String message;
while (!(message = in.readUTF()).equals("Over")) {
System.out.println("Message from client: " + message);
}
clientSocket.close();
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
21
}
}
for(i=2;i<=m;i++)
{
if(a%i==0)
{
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.writeUTF(a+" is not prime number");
flag=1;
break;
}
}
if(flag==0) {
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.writeUTF(a+" is prime number");
}
}
ss.close();
}
}

Output:-

22
Client.java:-

import java.io.*;
import java.net.*;

public class PrimeClient {


public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 12345);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {

BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));


System.out.println("Enter a number to check if it is prime (type 'exit' to quit):");

String userInputLine;
while (!(userInputLine = userInput.readLine()).equalsIgnoreCase("exit")) {
out.println(userInputLine);
String response = in.readLine();
System.out.println(response);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Output:-

23
4) WAP in java socket programming to check the given
number is Armstrong or not.

Server.java:-

import java.io.*;
import java.net.*;

public class ArmstrongServer {


public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(1234)) {
System.out.println("Server is listening on port 1234");

while (true) {
Socket socket = serverSocket.accept();
System.out.println("New client connected");

new ArmstrongHandler(socket).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

class ArmstrongHandler extends Thread {


private Socket socket;

public ArmstrongHandler(Socket socket) {


this.socket = socket;
}
@Override
public void run() {
try (BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {

24
String inputLine;
while ((inputLine = in.readLine()) != null) {
int number = Integer.parseInt(inputLine);
boolean isArmstrong = isArmstrong(number);
out.println("Number " + number + " is " + (isArmstrong ? "an Armstrong number." :
"not an Armstrong number."));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private boolean isArmstrong(int number) {
int originalNumber = number;
int result = 0;
int digits = String.valueOf(number).length();

while (number > 0) {


int digit = number % 10;
result += Math.pow(digit, digits);
number /= 10;
}

return result == originalNumber;


}
}
Output:-

25
Client.java:-
import java.io.*;
import java.net.*;

public class ArmstrongClient {


public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 1234);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {

BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));


System.out.println("Enter a number to check if it is an Armstrong number (type 'exit' to quit):");

String userInputLine;
while (!(userInputLine = userInput.readLine()).equalsIgnoreCase("exit")) {
out.println(userInputLine);
String response = in.readLine();
System.out.println(response);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Output:-

26
5) WAP in java socket programming to check the given
number is palindrome or not.
Server.java:-

import java.io.*;
import java.net.*;

public class PalindromeServer {


public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(12345)) {
System.out.println("Server is listening on port 12345");

while (true) {
Socket socket = serverSocket.accept();
System.out.println("New client connected");

new PalindromeHandler(socket).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

class PalindromeHandler extends Thread {


private Socket socket;

public PalindromeHandler(Socket socket) {


this.socket = socket;
}

@Override
public void run() {
try (BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {

27
String inputLine;
while ((inputLine = in.readLine()) != null) {
String response = isPalindrome(inputLine)
? inputLine + " is a palindrome."
: inputLine + " is not a palindrome.";
out.println(response);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

private boolean isPalindrome(String str) {


String reversed = new StringBuilder(str).reverse().toString();
return str.equals(reversed);
}
}

Output:-

28
Client.java:-

import java.io.*;
import java.net.*;

public class PalindromeClient {


public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 12345);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {

BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));


System.out.println("Enter a number to check if it is a palindrome (type 'exit' to quit):");

String userInputLine;
while (!(userInputLine = userInput.readLine()).equalsIgnoreCase("exit")) {
out.println(userInputLine);
String response = in.readLine();
System.out.println(response);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Output:-

29
6) WAP in java socket programming to check the given number is
even or odd.

Server.java:-

import java.io.*;
import java.net.*;

public class EvenOddServer {


public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(12345)) {
System.out.println("Server is listening on port 12345");

while (true) {
Socket socket = serverSocket.accept();
System.out.println("New client connected");

new EvenOddHandler(socket).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

class EvenOddHandler extends Thread {


private Socket socket;

public EvenOddHandler(Socket socket) {


this.socket = socket;
}

@Override
public void run() {
try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {

String inputLine;
while ((inputLine = in.readLine()) != null) {
try {
int number = Integer.parseInt(inputLine);
String response = isEven(number)
? number + " is even.

30
: number + " is odd.";
out.println(response);
} catch (NumberFormatException e) {
out.println("Please enter a valid integer.");
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

private boolean isEven(int number) {


return number % 2 == 0;
}
}

Output:-

31
Client.java:-

import java.io.*;
import java.net.*;

public class EvenOddClient {


public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 12345);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {

BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));


System.out.println("Enter a number to check if it is even or odd (type 'exit' to quit):");

String userInputLine;
while (!(userInputLine = userInput.readLine()).equalsIgnoreCase("exit")) {
out.println(userInputLine);
String response = in.readLine();
System.out.println(response);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

OUTPUT:-

32
7) WAP in java socket programming to find out the factorial of a
number using bind() function.

Server.java:-

import java.io.*;
import java.net.*;

public class FactorialServer {


public static void main(String[] args) {
try {
// Create a server socket and bind it to a port
ServerSocket serverSocket = new ServerSocket(12345);
System.out.println("Server is listening on port 12345");

while (true) {
// Accept client connections
Socket socket = serverSocket.accept();
System.out.println("New client connected");

// Handle the client in a separate thread


new FactorialHandler(socket).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

class FactorialHandler extends Thread {


private Socket socket;

public FactorialHandler(Socket socket) {

33
this.socket = socket;
}

@Override
public void run() {
try (BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {

String inputLine;
while ((inputLine = in.readLine()) != null) {

try {
int number = Integer.parseInt(inputLine);
long factorial = calculateFactorial(number);
out.println("Factorial of " + number + " is " + factorial);
} catch (NumberFormatException e) {
out.println("Please enter a valid integer.");
}
}
}
catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

34
private long calculateFactorial(int number) {
if (number < 0) return -1; // Factorial of negative numbers is not defined
long result = 1;
for (int i = 1; i <= number; i++) {
result *= i;
}
return result;
}
}

Output:-

35
Client.java:-

import java.io.*;
import java.net.*;

public class FibonacciClient {


public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 12345);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {

BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));


System.out.println("Enter a number to generate the Fibonacci series up to that number (type 'exit' to quit):");

String userInputLine;
while (!(userInputLine = userInput.readLine()).equalsIgnoreCase("exit")) {
out.println(userInputLine);
String response = in.readLine();
System.out.println(response);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Output:-

36
8) WAP in java socket programming to find out the Fibonacci
series.

Server.java:-

import java.io.*;
import java.net.*;

public class FactorialServer {


public static void main(String[] args) {
try {
// Create a server socket and bind it to a port
ServerSocket serverSocket = new ServerSocket(12345);
System.out.println("Server is listening on port 12345");

while (true) {
// Accept client connections
Socket socket = serverSocket.accept();
System.out.println("New client connected");

// Handle the client in a separate thread


new FactorialHandler(socket).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

class FactorialHandler extends Thread {


private Socket socket;

public FactorialHandler(Socket socket) {


this.socket = socket;
}

37
@Override
public void run() {
try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {

String inputLine;
while ((inputLine = in.readLine()) != null) {
try {
int number = Integer.parseInt(inputLine);
long factorial = calculateFactorial(number);
out.println("Factorial of " + number + " is " + factorial);
} catch (NumberFormatException e) {
out.println("Please enter a valid integer.");
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Output:-

38
Client.java:-

import java.io.*;
import java.net.*;

public class FibonacciClient {


public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 12345);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {

BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));


System.out.println("Enter a number to generate the Fibonacci series up to that numbe
r (type 'exit' to quit):");

String userInputLine;
while (!(userInputLine = userInput.readLine()).equalsIgnoreCase("exit")) {
out.println(userInputLine);
String response = in.readLine();
System.out.println(response);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Output:-

39
9) WAP in java socket programming to find out the largest among three
numbers using if else.

Server.java:-

import java.io.*;
import java.net.*;

public class LargestNumberServer {


public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(12345)) {
System.out.println("Server is listening on port 12345");

while (true) {
Socket socket = serverSocket.accept();
System.out.println("New client connected");

new LargestNumberHandler(socket).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

class LargestNumberHandler extends Thread {


private Socket socket;

public LargestNumberHandler(Socket socket) {


this.socket = socket;
}

@Override
public void run() {
try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {

String inputLine;
while ((inputLine = in.readLine()) != null) {
String[] numbers = inputLine.split(",");
if (numbers.length != 3) {
out.println("Please enter exactly three numbers separated by commas.");
continue;

40
}

try {
int num1 = Integer.parseInt(numbers[0].trim());
int num2 = Integer.parseInt(numbers[1].trim());
int num3 = Integer.parseInt(numbers[2].trim());

int largest = findLargest(num1, num2, num3);


out.println("The largest number is: " + largest);
} catch (NumberFormatException e) {
out.println("Please enter valid integers.");
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

private int findLargest(int num1, int num2, int num3) {


int largest;
if (num1 >= num2 && num1 >= num3) {
largest = num1;
} else if (num2 >= num1 && num2 >= num3) {
largest = num2;
} else {
largest = num3;
}
return largest;
}
}

Output:-

41
Client.java:-
import java.io.*;
import java.net.*;

public class LargestNumberClient {


public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 12345);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {

BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));


System.out.println("Enter three numbers separated by commas (e.g., 5, 10, 3):");

String userInputLine;
while ((userInputLine = userInput.readLine()) != null) {
out.println(userInputLine);
String response = in.readLine();
System.out.println(response);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Output:-

42
10) WAP to illustrate client side program of simple calculator
using TCP.
Client.java:-

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class CalculatorClient {


public static void main(String[] args) {
String serverAddress = "localhost"; // The server's IP address (or use "localhost" for local testing)
int port = 1234; // The port the server is listening on

try {
// Connect to the server
Socket socket = new Socket(serverAddress, port);
System.out.println("Connected to the server");

// Create input and output streams for communication


BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

// Create a scanner to get user input for the operation


Scanner scanner = new Scanner(System.in);

// Request operation and numbers from the user


System.out.println("Enter the first number: ");
double num1 = scanner.nextDouble();

System.out.println("Enter the second number: ");


double num2 = scanner.nextDouble();

System.out.println("Enter the operator (+, -, *, /): ");


String operator = scanner.next();

// Send the numbers and operator to the server


out.println(num1);
out.println(num2);
out.println(operator);

// Receive the result from the server


String result = in.readLine();
System.out.println("Result from the server: " + result);

43
// Close the resources
socket.close();
scanner.close();
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}

Output:-

44
11) WAP to illustrate server side program of simple calculator using TCP.

Server.java:-

import java.io.*;
import java.net.*;

public class CalculatorServer {


public static void main(String[] args) {
int port = 1234; // The port the server listens on

try {
// Create a server socket that listens on the specified port
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server is running and waiting for a client to connect...");

// Wait for a client connection


Socket clientSocket = serverSocket.accept();
System.out.println("Client connected!");

// Create input and output streams for communication


BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

// Read the numbers and operator from the client


double num1 = Double.parseDouble(in.readLine());
double num2 = Double.parseDouble(in.readLine());
String operator = in.readLine();

// Perform the calculation based on the operator


double result = 0;
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 != 0) {
result = num1 / num

45
} else {
out.println("Error: Division by zero!");
clientSocket.close();
serverSocket.close();
return;
}
break;
default:
out.println("Error: Invalid operator!");
clientSocket.close();
serverSocket.close();
return;
}

// Send the result back to the client


out.println("Result: " + result);

// Close the connection


clientSocket.close();
serverSocket.close();
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}

Output:-

46
12) WAP to illustrate client side program of simple calculator
using UDP.

Client.java:-

import java.net.*;
import java.io.*;
import java.util.Scanner;

public class CalculatorClientUDP {


public static void main(String[] args) {
String serverAddress = "localhost"; // The server's IP address (or use "localhost" for local testing)
int port = 9876; // The port the server is listening on

try {
// Create a DatagramSocket for UDP communication
DatagramSocket socket = new DatagramSocket();
InetAddress serverIP = InetAddress.getByName(serverAddress);

// Create a scanner to get user input for the operation


Scanner scanner = new Scanner(System.in);

// Request operation and numbers from the user


System.out.println("Enter the first number: ");
double num1 = scanner.nextDouble();

System.out.println("Enter the second number: ");


double num2 = scanner.nextDouble();

System.out.println("Enter the operator (+, -, *, /): ");


String operator = scanner.next();

// Prepare the message to send to the server


String message = num1 + " " + num2 + " " + operator;

// Send the message to the server


byte[] sendBuffer = message.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length, serverIP, port);
socket.send(sendPacket);

// Receive the result from the server


byte[] receiveBuffer = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
socket.receive(receivePacket);

// Print the result received from the server


String result = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Result from server: " + result);
47
// Close the socket and scanner
socket.close();
scanner.close();
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}

Output:-

48
13) WAP to illustrate server side program of simple
calculator using UDP.

Server.java:-

import java.net.*;
import java.io.*;

public class CalculatorServerUDP {


public static void main(String[] args) {
int port = 9876;

try {
// Create a DatagramSocket to listen for incoming requests
DatagramSocket socket = new DatagramSocket(port);
System.out.println("Server is running and waiting for client...");

while (true) {
// Receive the message from the client
byte[] receiveBuffer = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
socket.receive(receivePacket);

// Convert the received message into a string


String receivedMessage = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Received: " + receivedMessage);

// Split the message to extract numbers and operator


String[] parts = receivedMessage.split(" ");
double num1 = Double.parseDouble(parts[0]);
double num2 = Double.parseDouble(parts[1]);
String operator = parts[2];

// Perform the calculation


double result = 0;
String resultMessage = "";
switch (operator) {
case "+":
result = num1 + num2;
resultMessage = "Result: " + result;
break;
49
case "-":
result = num1 - num2;
resultMessage = "Result: " + result;
break;
case "*":
result = num1 * num2;
resultMessage = "Result: " + result;
break;
case "/":
if (num2 != 0) {
result = num1 / num2;
resultMessage = "Result: " + result;
} else {
resultMessage = "Error: Division by zero!";
}
break;
default:
resultMessage = "Error: Invalid operator!";
break;
}

// Send the result back to the client


byte[] sendBuffer = resultMessage.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length, receivePacket.getAddress(),
receivePacket.getPort());
socket.send(sendPacket);
}
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}

Output:-

50
14) WAP in java socket programming for client application in RMI.

Client.java:-

import java.rmi.Naming;

public class RMIClient {


public static void main(String[] args) {
try {
// Look up the remote object in the RMI registry
RMIServerInterface remoteObject = (RMIServerInterface) Naming.lookup("rm
i://localhost:1099/HelloService");

// Call the remote method and get the result


String response = remoteObject.sayHello("Client");

// Print the response from the server


System.out.println("Response from Server: " + response);

} catch (Exception e) {
e.printStackTrace();
}
}
}

Output:-

51
15) WAP in java socket programming for server application in RMI.

RMIServerInterface.java:-

import java.rmi.Remote;
import java.rmi.RemoteException;

// Define the remote interface


public interface RMIServerInterface extends Remote {
// Remote method to be called by the client
String sayHello(String name) throws RemoteException;
}

RMIServerImpl.java:-
import java.rmi.RemoteException;

import java.rmi.server.UnicastRemoteObject;

// Implementing the remote interface

public class RMIServerImpl extends UnicastRemoteObject implements RMIServerInterface {

// Constructor, must throw RemoteException

protected RMIServerImpl() throws RemoteException {

super();

// Implement the remote method

@Override

public String sayHello(String name) throws RemoteException {

return "Hello, " + name + "! Greetings from the RMI server.";

52
Server.java:-

import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;

public class RMIServer {


public static void main(String[] args) {
try {
// Start the RMI registry on port 1099 (default RMI port)
LocateRegistry.createRegistry(1099);

// Create an instance of the server implementation


RMIServerImpl server = new RMIServerImpl();

// Bind the remote object (server) in the RMI registry with a name
Naming.rebind("rmi://localhost:1099/HelloService", server);

System.out.println("RMI server is running...");

} catch (Exception e) {
e.printStackTrace();
}
}
}

Output:-

53
16) WAP to retrieve date and time using UDP.

Server.java:-

import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTimeServer {


public static void main(String[] args) {
int port = 9876; // Port number to listen on

try {
// Create a DatagramSocket to listen for incoming requests
DatagramSocket socket = new DatagramSocket(port);
System.out.println("DateTime Server is running on port " + port + "...");

while (true) {
// Buffer to receive incoming data
byte[] receiveBuffer = new byte[1024];

// Create a DatagramPacket to receive the request


DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
socket.receive(receivePacket);

// Get the current date and time


String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

// Send the current date and time back to the client


byte[] sendBuffer = currentTime.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length,
receivePacket.getAddress(),
receivePacket.getPort());
socket.send(sendPacket);

System.out.println("Sent current time to client: " + currentTime);


}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}

54
Output:-

55
Client.java:-
import java.net.*;
public class DateTimeClient {
public static void main(String[] args) {
String serverAddress = "localhost"; // Server address
int port = 9876; // Server port

try {
// Create a DatagramSocket for sending requests
DatagramSocket socket = new DatagramSocket();

// Prepare the request packet (empty request)


byte[] sendBuffer = new byte[1024];
DatagramPacket sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length,
InetAddress.getByName(serverAddress),
port);
socket.send(sendPacket); // Send the request

// Buffer to receive the response


byte[] receiveBuffer = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
socket.receive(receivePacket); // Receive the response

// Convert the response to a string and print it


String currentTime = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Current Date and Time: " + currentTime);

// Close the socket


socket.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}

Output:-

56
17) WAP to retrieve date and time using TCP.

Server.java:-

import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTimeServer {


public static void main(String[] args) {
int port = 9876; // Port number to listen on

try {
// Create a DatagramSocket to listen for incoming requests
DatagramSocket socket = new DatagramSocket(port);
System.out.println("DateTime Server is running on port " + port + "...");

while (true) {
// Buffer to receive incoming data
byte[] receiveBuffer = new byte[1024];

// Create a DatagramPacket to receive the request


DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
socket.receive(receivePacket);

// Get the current date and time


String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

// Send the current date and time back to the client


byte[] sendBuffer = currentTime.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length,
receivePacket.getAddress(),
receivePacket.getPort());
socket.send(sendPacket);

System.out.println("Sent current time to client: " + currentTime);


}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}

57
Output:-

58
Client.java:-

import java.io.*;
import java.net.*;

public class DateTimeClientTCP {


public static void main(String[] args) {
String serverAddress = "localhost"; // Server address
int port = 6789; // Server port

try (Socket socket = new Socket(serverAddress, port)) {


// Create input and output streams
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));

// Send a request to the server


out.println("GET_CURRENT_TIME"); // Optional request
System.out.println("Sent request to server.");

// Read the response from the server


String currentTime = in.readLine();
System.out.println("Current Date and Time: " + currentTime);

} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}

Output:-

59
18) Program for connection-oriented Iterative Service
in which server reverses the string sent by the client
and sends it back.

Server.java:-

// Importing necessary libraries


import java.io.*;
import java.net.*;

public class ReverseServer {


public static void main(String[] args) {
int port = 1234; // Server listens on this port

try (ServerSocket serverSocket = new ServerSocket(port)) {


System.out.println("Server is listening on port " + port);

// Infinite loop for iterative service


while (true) {
// Accept a client connection
Socket socket = serverSocket.accept();
System.out.println("New client connected");

// Create input and output streams for communication


InputStream input = socket.getInputStream();
BufferedReader reader = new BufferedReader(new
InputStreamReader(input));

OutputStream output = socket.getOutputStream();


PrintWriter writer = new PrintWriter(output, true);

// Read the client's message


String message = reader.readLine();
System.out.println("Received from client: " + message);

// Reverse the string


String reversedMessage = new StringBuilder(message).reverse().toString();

// Send the reversed string back to the client


writer.println(reversedMessage);
System.out.println("Reversed string sent back to client");

// Close the connection with the current client


socket.close();
}

60
} catch (IOException e) {
e.printStackTrace();
}
}
}

Output:-

61
Client.java:-

// Importing necessary libraries


import java.io.*;
import java.net.*;

public class ReverseClient {


public static void main(String[] args) {
String hostname = "localhost"; // Server address
int port = 1234; // Server port number

try (Socket socket = new Socket(hostname, port)) {


// Create input and output streams for communication
OutputStream output = socket.getOutputStream();
PrintWriter writer = new PrintWriter(output, true);

InputStream input = socket.getInputStream();


BufferedReader reader = new BufferedReader(new InputStreamReader(input));

// Send a string to the server


String message = "Hello World";
writer.println(message);
System.out.println("Sent to server: " + message);

// Read the server's response


String reversedMessage = reader.readLine();
System.out.println("Received from server: " + reversedMessage);

} catch (UnknownHostException e) {
System.out.println("Server not found: " + e.getMessage());
} catch (IOException e) {
System.out.println("I/O error: " + e.getMessage());
}
}
}

Output:-

62
19) Program for connection-oriented Iterative service in
which server changes the case of the strings sent by
the client and sends back (Case Server).

Server.java:-

import java.io.*;
import java.net.*;

public class StringCaseConverterServer {


public static void main(String[] args) {
int port = 56778; // Server port
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("Server is listening on port " + port);
while (true) {
try (Socket socket = serverSocket.accept()) {
System.out.println("New client connected");
handleClient(socket);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}

private static void handleClient(Socket socket) {


try (BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true)) {

String clientInput;
while ((clientInput = input.readLine()) != null) {
String response = convertCase(clientInput);
output.println(response);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}

private static String convertCase(String input) {


// Check if the input is in lower case or upper case and convert accordingly

63
if (input.equals(input.toLowerCase())) {

return input.toUpperCase(); // Convert to upper case


} else {
return input.toLowerCase(); // Convert to lower case
}
}
}

import java.net.*;
import java.io.*;
import java.util.*;
public class server{
public static void main(String [] args)throws IOException{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();

DataInputStream dis = new DataInputStream(s.getInputStream());


String str = (String)dis.readUTF();
System.out.println("Message from Client: "+str);
String str1=str.toUpperCase();
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.writeUTF(str1);
ss.close();
}
}

Output:-

64
Client.java:-

import java.io.*;
import java.net.*;

public class StringCaseConverterClient {


public static void main(String[] args) {
String serverAddress = "localhost"; // Server address
int port = 56778; // Server port

try (Socket socket = new Socket(serverAddress, port);


PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in))) {

System.out.println("Connected to the server. Type your messages (type 'exit' to quit):");

String userInput;
while (!(userInput = consoleInput.readLine()).equalsIgnoreCase("exit")) {
output.println(userInput);
String response = input.readLine();
System.out.println("Server response: " + response);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

Output:-

65
20) WAP in java socket programming to demonstrate working of URL.

import java.io.*;
import java.net.*;

public class URLFetcher {


public static void main(String[] args) {
String hostname = "google.com"; // Change this to the desired URL hostname
String path = "/"; // The path of the resource on the server (e.g., "/" for homepage)
int port = 80; // Default HTTP port

try {
// Create a socket to connect to the web server
Socket socket = new Socket(hostname, port);

// Create an output stream to send the HTTP GET request


PrintWriter out = new PrintWriter(socket.getOutputStream());

// Form and send the HTTP GET request


out.print("GET " + path + " HTTP/1.1\r\n");
out.print("Host: " + hostname + "\r\n");
out.print("Connection: close\r\n");
out.print("\r\n");
out.flush();

// Create an input stream to receive the server's response


BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

// Read and print the response


String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}

// Close the input/output streams and the socket


in.close();
out.close();
socket.close();
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}

66
Output:-

67

You might also like