File Transfer

 

Write a network program to transfer a file from the server to the client.

Server.java


import java.io.*;
import java.net.*;
class Server
{
	public static void main(String args[]) throws Exception
	{
		ServerSocket ss=new ServerSocket(7632);
		System.out.println("The server is waiting for the
client.");
		Socket s= ss.accept();
		System.out.println("The client is connected.");
		BufferedReader br= new BufferedReader(new
InputStreamReader(s.getInputStream()));
		String name=br.readLine();

		PrintWriter pr=new PrintWriter(s.getOutputStream());

		String str;
		BufferedReader fileReader= new BufferedReader(new
InputStreamReader(new FileInputStream(name)));
		while((str=fileReader.readLine())!=null)
		{
			//System.out.println(str);
			pr.println(str);
			pr.flush();
		}
		System.out.print("\n\nFile transfer completed.");
		s.close();
		ss.close();
	}
}

Client.java


import java.io.*;
import java.net.*;
class Client
{
	public static void main(String args[]) throws Exception
	{
		Socket s= new Socket("localhost",7632);
		System.out.println("The client is connected to the
server.");
		System.out.println("\n\nEnter the name of the file that you
want to download from the Server: ");
BufferedReader br= new BufferedReader(new
InputStreamReader(System.in));
		PrintWriter pr= new PrintWriter(s.getOutputStream());
		pr.println(br.readLine());
		pr.flush();

		BufferedReader fromServer= new BufferedReader(new
InputStreamReader(s.getInputStream()));

		File f= new File("Downloaded_file.txt");
		String str;
		byte b[];
		FileOutputStream fos=new FileOutputStream(f);
		while((str=fromServer.readLine())!=null)
		{
			b=str.getBytes();
			fos.write(b);
		}
		System.out.println("File recieved successfully.");
		s.close();
	}
}

Output

 

 

Terminal 1 Terminal 2
>java Server> The server is waiting for the client.

> The client is connected.

 

 

 

 

 

> File transfer completed.

 

 

 

>java Client

>The client is connected to the server.

>Enter the name of the file that you want to download from the Server: marks.txt

 

> File recieved successfully

 

Leave a Reply

Your email address will not be published. Required fields are marked *