0% found this document useful (0 votes)
25 views

Lab Report 3

Report

Uploaded by

222902019
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Lab Report 3

Report

Uploaded by

222902019
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Green University of Bangladesh

Department of Computer Science and Engineering (CSE)


Faculty of Sciences and Engineering
Semester: Fall, Year: 2024, B.Sc. in CSE (Day)

LAB REPORT 03
Course Title: Computer Networking Lab
Course Code: CSE 312 Section: 222 D2

Lab Experiment Name: Implementation of socket programming using threading.

Student Details

Name ID

Afiya Humaira 222002112

Lab Date : 13-11-2024


Submission Date : 20-11-2024
Course Teacher’s Name : Rusmita Halim Chaity

[For Teachers use only: Don’t Write Anything inside this box]

Lab Report Status


Marks: ………………………………… Signature:.....................
Comments:.............................................. Date:..............................
TITLE OF THE LAB EXPERIMENT:
Implementation of socket programming using threading.

OBJECTIVES/AIM:
• To Establish Communication Using TCP Protocol.
• To Develop a Server Application and Design a Client Application.
• To Support Multiple Client Connections.
• To gather basic knowledge of socket programming using threading.
• To Facilitate User Interaction and Input Validation.
• To Support Mathematical Operations.

PROCEDURE / ANALYSIS / DESIGN:


Algorithm:
1. Start a ServerSocket on port 5000.
2. Print a message indicating the server is ready.
3. Initialize clientCount to track the number of connected clients.
4. Accept a client connection (Socket com_socket = handshake.accept()).
5. Increment clientCount.
6. Print connection details.
7. Create DataInputStream and DataOutputStream for the client.
8. Create and start a new thread (ClientHandler) for handling client interaction.
9. If clientCount reaches 5, print a shutdown message and close the ServerSocket.
10. Set up DataInputStream and DataOutputStream for the connected client.
11. Repeat until the client sends the termination command ("ENDS"):
12. Send a prompt to the client requesting two integers and an operator.
13. Receive input from the client.
14. If the input is "ENDS":
15. Print a message that the client is disconnecting.
16. Close the connection and break the loop.
17. Split the input string into parts.
18. If input format is invalid:
19. Send an error message to the client and continue.
20. Parse the two integers.
21. Identify the operator and perform the corresponding operation:
22. Sum: Add the two integers and send the result.
23. Subtract: Subtract the second integer from the first and send the result.
24. Multiplication: Multiply the integers and send the result.
25. Division: If the second integer is not zero, divide and send the result. Otherwise, send an
error message.
26. Modules: Find the modulus and send the result.
27. If the operator is invalid, send an error message to the client.
28. Ensure that DataInputStream and DataOutputStream are closed when the thread finishes.
29. Create a Socket to connect to the server on localhost at port 5000.
30. Print a connection confirmation message.
31. Repeat until the user inputs "ENDS":
32. Receive and print the server's prompt.
33. Read user input from the console.
34. Send the input to the server.
35. If the input is "ENDS":
36. Close the connection and break the loop.
37. Receive and print the server's response (result or error message).

IMPLEMENTATION:
Problem: Mathematical operations are very useful to be implemented using TCP socket
programming. Create two processes, a server and a client using JAVA codes. The client will send
two separate integer values and a mathematical operator to the server. The server receives these
integers and a mathematical operator, then performs a mathematical operation based on the user
input. The server then sends this answer to the client, who then displays it. The client sends requests
as many times as he wishes. However, The server can serve at most 5 clients in its lifetime. The
individual client ends its connection by saying “ENDS”. For example:
• If the client sends 10, 20, and Sum, the server sends 30 to the client.
• If the client sends 20, 5, and Subtract, the server sends 15 to the client.
• If the client sends 20, 5, and Multiplication, the server sends 100 to the client.
• If the client sends 20, 5, and Division, the server sends 4 to the client.
• If the client sends 16, 3, and Modules, the server sends 1 to the client.

ServerThread ClientThread
package javaapplication11; package javaapplication11;

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


import java.net.*; import java.net.*;
import import java.util.Scanner;
java.util.concurrent.atomic.AtomicInteger;
public class ClientThread {
public class ServerThread { private static final String
private static final int MAX_CLIENTS = 5; SERVER_ADDRESS = "localhost";
private static final int PORT = 5000; private static final int PORT = 5000;
private static AtomicInteger clientCount = new
AtomicInteger(0); public static void main(String[] args) {
try (Socket socket = new
public static void main(String[] args) { Socket(SERVER_ADDRESS, PORT)) {
try (ServerSocket serverSocket = new System.out.println("Connected to
ServerSocket(PORT)) { the server at port " + PORT);
System.out.println("Server started at port
" + PORT); DataInputStream dis = new
System.out.println("Ready to accept DataInputStream(socket.getInputStream());
clients..."); DataOutputStream dos = new
DataOutputStream(socket.getOutputStrea
while (true) { m());
if (clientCount.get() >= Scanner scanner = new
MAX_CLIENTS) { Scanner(System.in);
System.out.println("Maximum
client limit reached. No more connections will be while (true) {
accepted.");
break; System.out.println(dis.readUTF());
} String userInput =
scanner.nextLine();
Socket clientSocket = dos.writeUTF(userInput);
serverSocket.accept();
clientCount.incrementAndGet(); if
System.out.println("New client (userInput.equalsIgnoreCase("ENDS")) {
connected: " + clientSocket); System.out.println("Closing
the connection...");
DataInputStream dis = new break;
DataInputStream(clientSocket.getInputStream()) }
;
DataOutputStream dos = new String response = dis.readUTF();
DataOutputStream(clientSocket.getOutputStrea System.out.println(response);
m()); }
} catch (IOException e) {
Thread clientThread = new System.err.println("Client error: " +
ClientHandler(clientSocket, dis, dos); e.getMessage());
clientThread.start(); }
} }
} catch (IOException e) { }
System.err.println("Server error: " +
e.getMessage());
}
}
}

class ClientHandler extends Thread {


private final Socket clientSocket;
private final DataInputStream dis;
private final DataOutputStream dos;
public ClientHandler(Socket clientSocket,
DataInputStream dis, DataOutputStream dos) {
this.clientSocket = clientSocket;
this.dis = dis;
this.dos = dos;
}

@Override
public void run() {
try {
while (true) {
dos.writeUTF("Enter two integers and
an operator (Sum, Subtract, Multiplication,
Division, Modules), or type 'ENDS' to close
connection:");

String input = dis.readUTF();


if (input.equalsIgnoreCase("ENDS")) {
System.out.println("Client requested
to end the connection: " + clientSocket);
clientSocket.close();
break;
}

String[] parts = input.split(" ");


if (parts.length != 3) {
dos.writeUTF("Invalid input.
Format: <int1> <int2> <operator>. Try again.");
continue;
}

try {
int num1 =
Integer.parseInt(parts[0]);
int num2 =
Integer.parseInt(parts[1]);
String operator =
parts[2].toLowerCase();
String result;

switch (operator) {
case "sum":
result = String.valueOf(num1 +
num2);
break;
case "subtract":
result = String.valueOf(num1 -
num2);
break;
case "multiplication":
result = String.valueOf(num1 *
num2);
break;
case "division":
result = (num2 != 0) ?
String.valueOf(num1 / num2) : "Error: Division
by zero.";
break;
case "modules":
result = String.valueOf(num1
% num2);
break;
default:
result = "Invalid operator. Use:
Sum, Subtract, Multiplication, Division, or
Modules.";
break;
}

dos.writeUTF("Result: " + result);


} catch (NumberFormatException e) {
dos.writeUTF("Error: Please
provide valid integers.");
}
}
} catch (IOException e) {
System.err.println("Error handling client:
" + e.getMessage());
} finally {
try {
dis.close();
dos.close();
} catch (IOException e) {
System.err.println("Error closing
resources: " + e.getMessage());
}
}
}
}
TEST RESULT / OUTPUT:
ANALYSIS AND DISCUSSION:
The server-client program developed met all the requirements for handling basic mathematical
operations over a TCP connection. The server, which supported multi-threading, processed client
requests for addition, subtraction, multiplication, division (with checks for zero), and modulus,
responding appropriately and limiting connections to 5 clients before shutting down.
Key strengths included smooth multi-threading, effective user input handling, stable
communication using `DataInputStream` and `DataOutputStream`, and robust error management.
Challenges were faced in managing concurrent connections, ensuring resource closure, and
implementing comprehensive exception handling.
The assignment was practical and reinforced skills in TCP socket programming, thread
management, error handling, and input validation. All objectives were met, including developing
a multi-threaded server, client application, input validation, mathematical processing, and reliable
communication. This project enhanced understanding of network programming and multi-
threaded client-server architecture.

You might also like