0% found this document useful (0 votes)
12 views5 pages

TCP/IP Client-Server File Transfer Code

CN

Uploaded by

Vansh Gupta
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)
12 views5 pages

TCP/IP Client-Server File Transfer Code

CN

Uploaded by

Vansh Gupta
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

Experiment 7: Client-Server Program using TCP/IP sockets 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.

TCPServer Program:

import [Link].*;

import [Link].*;

public class TCPServer {

public static void main(String args[]) throws Exception {

// Create a server socket on port 4000

ServerSocket serverSocket = new ServerSocket(4000);

[Link]("Server ready for connection...");

// Wait for a client to connect

Socket socket = [Link]();

[Link]("Connection successful. Waiting for file request...");

// Get filename from client

BufferedReader fileRequest = new BufferedReader(new


InputStreamReader([Link]()));

String fileName = [Link]();

[Link]("Client requested file: " + fileName);

// Read contents of the file

BufferedReader fileReader;

try {
fileReader = new BufferedReader(new FileReader(fileName));

} catch (FileNotFoundException e) {

PrintWriter errorWriter = new PrintWriter([Link](),


true);

[Link]("ERROR: File not found on server.");

[Link]();

[Link]();

return;

// Prepare to send file content

PrintWriter writer = new PrintWriter([Link](), true);

String line;

while ((line = [Link]()) != null) {

[Link](line);

[Link]("File transfer completed.");

// Close everything

[Link]();

[Link]();

[Link]();

[Link]();

[Link]();

}
TCPClient Program:

import [Link].*;

import [Link].*;

public class TCPClient {

public static void main(String args[]) throws Exception {

// Connect to server

Socket socket = new Socket("[Link]", 4000);

// Read filename from keyboard

[Link]("Enter the file name: ");

BufferedReader userInput = new BufferedReader(new


InputStreamReader([Link]));

String fileName = [Link]();

// Send filename to server

PrintWriter writer = new PrintWriter([Link](), true);

[Link](fileName);

// Receive and print file contents

BufferedReader socketReader = new BufferedReader(new


InputStreamReader([Link]()));

String line;

[Link]("\n--- File contents received from server ---\n");

while ((line = [Link]()) != null) {

[Link](line);

}
// Close all connections

[Link]();

[Link]();

[Link]();

[Link]();

Common questions

Powered by AI

The flow of information begins with the server creating a ServerSocket on a specific port (4000) and waiting for a client connection. Once a client connects, the server accepts it, creating a Socket for communication. The client reads the filename from the keyboard and sends it to the server. The server receives the filename, attempts to read the file, and sends the file contents line-by-line back to the client. The client receives and displays the file content. Finally, the client and server both close their respective connections to end the session .

The main components involved include: the ServerSocket on port 4000 for listening to client connections, the Socket object for establishing the connection between the client and server, a BufferedReader for reading the requested file from the server's filesystem, a PrintWriter for sending the file's content back to the client, and additional BufferedReader and PrintWriter objects on the client side to respectively send the filename to the server and receive the file content .

This TCP server-client model exemplifies client-server architecture by clearly delineating roles where the server provides data resources, and the client requests this data. The server listens on a specific port for client connections and fulfills requests by processing input (the filename) and outputting the file's data. The client initiates the communication, specifies the needed resource, and handles the server's response, showcasing the core principle of the client requesting services from a server that then processes and responds to these requests .

Streams play a critical role in the communication between TCPClient and TCPServer by facilitating the flow of data. Input and Output streams are used to send data across the socket. On the server side, BufferedReader reads data from the client via InputStreamReader, enabling receiving filenames. PrintWriter outputs data from the server to the client, sending back file contents. Conversely, the client uses PrintWriter to send the filename and BufferedReader to read the transmitted file contents. These streams ensure that data is efficiently transmitted and received in a controlled manner .

To handle multiple client requests simultaneously, the server can be improved by implementing multithreading. This involves creating a new thread to handle each client connection as it comes in. The server's main thread can continue listening for new connections while individual threads manage the input/output operations for different clients. This allows the server to process multiple requests concurrently, enhancing scalability and responsiveness under increased load .

When the TCP server receives a file request and determines that the requested file does not exist, it handles the situation by catching a FileNotFoundException. In this case, the server creates a new PrintWriter object, writes an error message ('ERROR: File not found on server.') to the client, and then closes the socket and server socket to end the connection .

This TCP socket implementation ensures reliable file transfer by using TCP's inherent features like guaranteed delivery and ordered data transfer. The server reads the file line-by-line using a BufferedReader and sends each line to the client using a PrintWriter. The client then reads each line through BufferedReader, ensuring that the entire file, line-by-line, is transferred and printed .

Using port 4000 in this implementation is arbitrary but functional for demonstration. In practice, choosing a port involves considerations such as avoiding well-known ports (0–1023) used by system services unless legally required, considering ports already in use on the server to prevent conflicts, and potentially using higher-numbered ports (49152 to 65535) for custom services to minimize collision risks. Security concerns and firewall configurations should also be addressed to ensure accessibility while maintaining secure communications .

Not properly handling exceptions like FileNotFoundException could result in the server failing to notify clients of errors, leaving them uncertain about the status of their requests. It could also cause the server to crash if the exception triggers unexpected behavior, potentially halting service for all clients. Therefore, handling exceptions is crucial to maintaining robust server operations and providing meaningful feedback to clients, thus improving overall reliability and user experience .

It is important to close all connections after receiving the file contents to free up system resources and avoid potential memory leaks. Closing connections properly ensures that sockets are released for other applications or processes. Additionally, it helps to prevent connection exhaustion on the server, maintaining server availability and performance for handling more client requests .

You might also like