0% found this document useful (0 votes)
11 views7 pages

TCP Socket Student Result System

Uploaded by

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

TCP Socket Student Result System

Uploaded by

skirubasri751
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

[Link].

08 TCP SOCKET PROGRAM


DATE:20.09.25

[Link]:

A college wants to set up a Student Result Query System using TCP sockets. A server
maintains a list of students with their marks and grades. Multiple clients (students) connect to
the server to request their results.
ALGORITHM(SERVER):

1. Start server socket at port (e.g., 5000).


2. Input number of students and their roll numbers + marks.
3. Calculate grade dynamically for each student.
4. Wait for client connection.
5. Read roll number sent by client.
6. Search in stored data.
If found → send marks and grade.
Else → send “Result not available”.
7. Close client connection and wait for next client.

ALGORITHM(CLIENT):

1. Connect to server at given port.


2. Input roll number from user.
3. Send roll number to server.
4. Receive result from server.
5. Display result.
6. Close connection.

CODE:

SERVER:

import [Link].*;
import [Link].*;
import [Link];
public class resultserver {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(5000);
[Link]("Server started. Waiting for clients...");
Scanner sc = new Scanner([Link]);
[Link]("Enter number of students: ");
int n = [Link]();
[Link]();
String[] rollnos = new String[n];
String[] results = new String[n];
for (int i = 0; i < n; i++) {
[Link]("Enter roll number for student " + (i+1) + ": ");
rollnos[i] = [Link]();
[Link]("Enter marks: ");
int marks = [Link]();
[Link]();
String grade;
if (marks >= 80) grade = "A";
else if (marks >= 60) grade = "B";
else if (marks >= 40) grade = "C";
else grade = "Fail";
results[i] = "Marks: " + marks + ", Grade: " + grade;}
while (true) {
Socket socket = [Link]();
[Link]("Client connected: " + socket);
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
PrintWriter out = new PrintWriter([Link](), true);
String rollno = [Link]();
[Link]("Query received for Roll No: " + rollno);
String result = "Result not available";
for (int i = 0; i < [Link]; i++) {
if (rollnos[i].equals(rollno)) {
result = results[i];
break;
}}
[Link](result);
[Link]();
[Link]("Client disconnected.");
}}}
CLIENT:
import [Link].*;
import [Link].*;
public class resultclient {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost", 5000);
[Link]("Connected to server.");
BufferedReader userInput = new BufferedReader(new InputStreamReader([Link]));
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
PrintWriter out = new PrintWriter([Link](), true);
[Link]("Enter Roll Number: ");
String rollno = [Link]();
[Link](rollno);
String result = [Link]();
[Link]("Result: " + result);
[Link]();
[Link]("Disconnected from server."); }}
OUTPUT:

2. AIM:
Design a Chat Application using UDP sockets. The server and client should be able to
exchange short text messages.

ALGORITHM:
SERVER:
1. Create UDP socket at a port (e.g., 6000).
2. Continuously receive messages from client.
3. Display received message.
4. If message is "exit" → stop communication.
5. Else, take reply message from server user.
6. Send reply back to client.
7. Repeat until "exit" is received or sent.
8. Close socket.

CLIENT:

1. Create UDP socket.


2. Enter message from user.
3. Send message to server.
4. If message is "exit" → stop communication.
5. Else, wait for server reply.
6. Display reply.
7. Repeat until "exit" is sent or received.
8. Close socket.
CODE:
SERVER:
import [Link].*;
import [Link];
public class chatserver {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(6000);
byte[] buffer = new byte[1024];
Scanner sc = new Scanner([Link]);
[Link]("UDP Chat Server started...");
while (true) {
DatagramPacket packet = new DatagramPacket(buffer, [Link]);
[Link](packet);
String msg = new String([Link](), 0, [Link]());
[Link]("Client: " + msg);
if ([Link]("exit")) {
[Link]("Client ended chat. Closing server...");
break;}
[Link]("Server: ");
String reply = [Link]();
byte[] replyData = [Link]();
DatagramPacket replyPacket = new DatagramPacket(replyData, [Link],
[Link](), [Link]());
[Link](replyPacket);
if ([Link]("exit")) {
[Link]("Server ended chat.");
break;}}
[Link](); }}
CLIENT:
import [Link].*;
import [Link];
public class chatclient {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
InetAddress serverAddress = [Link]("localhost");
Scanner sc = new Scanner([Link]);
[Link]("Connected to UDP Chat Server.");
[Link]("Type messages to send (type 'exit' to quit):");
while (true) {
[Link]("Client: ");
String msg = [Link]();
byte[] sendData = [Link]();
DatagramPacket sendPacket = new DatagramPacket(sendData, [Link],
serverAddress, 6000);
[Link](sendPacket);
if ([Link]("exit")) {
[Link]("Client ended chat.");
break;}
byte[] buffer = new byte[1024];
DatagramPacket replyPacket = new DatagramPacket(buffer, [Link]);
[Link](replyPacket);
String reply = new String([Link](), 0, [Link]());
[Link]("Server: " + reply);
if ([Link]("exit")) {
[Link]("Server ended chat.");
break; }}
[Link]();}}
OUTPUT:

RESULT:
Thus the given tcp socket programming was executed and verified successfully.

Common questions

Powered by AI

The student result system could be enhanced by incorporating a database to persist student records beyond runtime, allowing for data retrieval and updating without manual re-entry. Implementing authentication measures for accessing results could improve security and prevent unauthorized access. Adding input validation would improve data accuracy by ensuring only valid roll numbers and marks are accepted. Providing a web-based interface or mobile app could enhance accessibility and user experience, offering features like results history, notifications, and analytics.

The scalability of the UDP chat server code is constrained by its single-threaded design, which processes all incoming messages sequentially. While UDP's stateless and connectionless nature theoretically supports high throughput, the server's design limits it to handling one message at a time in a blocking manner. This can become a bottleneck if multiple messages are received rapidly, potentially leading to latency in message delivery. Additionally, the lack of client-session management may hinder scalability when trying to maintain conversation contexts across many users simultaneously.

To protect data exchanged in TCP and UDP applications, encryption of the data streams is crucial, ensuring confidentiality and integrity against interception and tampering. For TCP connections, utilizing TLS can secure communication. Implementing authentication mechanisms ensures only authorized clients and servers connect and exchange information. Input validation and sanitization can prevent injection attacks. Monitoring network traffic for anomalies and employing firewalls can mitigate unauthorized access and DDoS attacks. UDP communication should limit broadcast to prevent spoofing, and both applications should implement logging and auditing practices to detect and respond to security incidents promptly.

The TCP server calculates grades dynamically upon receiving student information, using a straightforward conditional logic to assign grades based on marks. This approach ensures that grades are consistently calculated whenever new data is input. While the logic is efficient due to its simplicity, providing near-instantaneous processing for each query, it assumes input accuracy, and any errors in data entry directly affect reliability. Additionally, any changes to grading criteria require modification in the code, potentially introducing errors if not handled carefully.

The choice of ports, such as 5000 for TCP and 6000 for UDP, acts as specific endpoints for the respective application protocols running on the server. Ports must be unique and not in use by other applications on the same host. For real-world deployment, higher non-privileged ports are commonly chosen to avoid conflicts with well-known services. Network and firewall configurations need to allow traffic on these ports to ensure connectivity, and considerations for security and port management are necessary to prevent unauthorized access and potential vulnerabilities.

Using blocking I/O methods, as seen in the TCP and UDP examples, means that the server or client waits for operations like read and write to complete before proceeding. This can simplify program logic since it ensures one operation completes before starting the next, though it may lead to inefficiency by idling during waits. In a heavily loaded system, blocking I/O can result in resource underutilization, reduced throughput, and potentially limit scalability, as a single blocked operation can stall the entire application's responsiveness, suggesting non-blocking or asynchronous approaches for high-performance needs.

The TCP socket-based system ensures accurate result retrieval by maintaining a unique connection for each client through sockets. The server listens for incoming connections and uses a separate socket object for each accepted connection, allowing it to handle multiple clients simultaneously. Each client sends a roll number, and the server searches for the corresponding student in its data. The use of blocking I/O methods ensures that each client receives its specific result, as the server handles requests sequentially, processing the complete transaction for one client before accepting another connection.

In the Student Result Query System using TCP, a connection-oriented protocol is used, meaning a dedicated connection is established between server and client before data is exchanged. This ensures reliable delivery of messages in the correct order, crucial for tasks like result queries where accuracy is paramount. The server uniquely identifies each client by its socket connection, allowing it to manage state across multiple sessions. In contrast, the UDP-based Chat Application uses a connectionless approach, where messages are sent to the server or client without establishing a dedicated connection, resulting in less overhead and faster communication, but without guarantees of delivery or order, suitable for real-time communication where speed is prioritized over reliability.

The TCP server uses a loop to continuously accept client connections to handle multiple student queries in succession. This design allows the server to remain available for new client connections without restarting, providing an uninterrupted service. However, potential issues include the risk of resource exhaustion if clients connect more rapidly than they can be processed, leading to unresponsive behavior or the server exceeding its maximum number of simultaneous connections, and the lack of concurrency that limits scalability by handling connections sequentially rather than in parallel.

In the UDP-based chat application, data packets are used to send messages between the server and client without establishing a persistent connection. Each message is encapsulated in a datagram packet and sent over the network immediately, providing low latency. Unlike TCP, which uses a stream-oriented approach ensuring message order and error-checking, UDP's datagram packets are independent, without inherent reordering or error correction, making UDP suitable for simple or real-time applications like chat services where speed is critical.

You might also like