Let us write client and server programs, such that the client sends the name of a file to the server. After receiving the file name, the server searches for the file to know if it exists or not. If the file exists, the server send the file contents to the client.
Program:
Write a program that accepts the filename and checks for its existence. When the file exists at server side, it sends its contents to the client.
// A server that sends a file content to the client
import java.io.*; import java.net.*; classFileServer { public static void main(String args[]) throws Exception { // creates server socket ServerSocketss=new ServerSocket(8888); // make the server wait till a client accepts connection Socket s=ss.accept(); System.out.println(“Connection Established”); // to accept file name from client BufferReader in=new BufferReader(new InputStreamReader(s.getInputStream())); // to send file content to client DataOutputStream out=new DataOutputStream(s.getOutputStream()); // read the filename from the client String fname=in.readLine(); FileReaderfr=null; BufferedReader file=null; boolean flag; // create File class object with filename File f=new File(fname); // test if file exists or not if(f.exists)) flag=true; else flag=false; // if file exists, send “Yes” to client, else send “No” if(flag==true) out.writeBytes(“Yes”+”\n”); elseout.writeBytes(“No”+”\n”); if(flag==true) { // attach file to the FileReader to read data fr=new FileReader(fname); // attach FileReader to BufferedReader file=new BufferedReader(fr); String str; // read from BufferedReader and write to DataOutputStream while((str=readLine()) !=null) { out.writeBytes(str+”\n”); } file.close(); out.close(); in.close(); fr.close(); s.close(); ss.close(); } } }
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc