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

Program 7

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)
2 views5 pages

Program 7

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]();

You might also like