Skip to main content

Implement a file server to transfer a file from server side to client side.

Implement a file server to transfer a file from server side to client side.



Server-side


import java.net.*;
import java.io.*;
public class ftpserv
{
public static void main(String args[]) throws Exception
{
ServerSocketss = null;
Socket s = null;
try
{
ss = new ServerSocket(4000);
System.out.println("Connecting with client");
s = ss.accept();
System.out.println("Connection is successful");
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String str = br.readLine( );
BufferedReader br2= new BufferedReader(new FileReader(str) );
System.out.println("File found");
// keeping output stream ready to send the contents
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
String str2;
while((str2 = br2.readLine()) != null) // reading line-by-line from file
{
pw.println(str2); // sending each line to client
}
System.out.println("File send successfully");
}
catch (SocketException e)
{ System.out.println(e);}
catch (FileNotFoundException e)
{
System.out.println("File does not exist");
}
catch (IOException e)
{ System.out.println(e); }
catch (Exception e) { System.out.println(e); }
finally
{
s.close();
ss.close(); // closing network sockets
}}}





Client side


import java.net.*;
import java.io.*;
public class ftpclient
{
public static void main( String args[ ] ) throws Exception
{
Socket s = null;
try
{
s = new Socket( "localhost", 4000);
System.out.print("Enter path of file atserver: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
pw.println(str);
BufferedReader br2 = new BufferedReader(new InputStreamReader(s.getInputStream()));
String str2;
System.out.print("Enter new path of file at client: ");
str2= br.readLine();
BufferedWriter bw = new BufferedWriter(new FileWriter(str2));
while((str2 = br2.readLine()) != null) // reading line-by-line
{
bw.write(str2); bw.newLine();
}
bw.close();
System.out.println("File saved");
}
catch (SocketException e)
{ System.out.println(e); }
catch (FileNotFoundException e)
{
System.out.println("File does not exist");
}
catch (IOException e)
{ System.out.println(e); }
catch (Exception e)
{ System.out.println(e); }
finally
{
s.close();
}}}

Comments