Socket program for client give the file name and file path name and server will read the file and send back to client of the file conetent date for print to console


NB: if using remote path please share the folder where you pickup the file exist other wise it will give the security issue

Step 1>SocketServerExample  Run in different  Server or eclipse

package com.kartik.socket;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * This class implements java Socket server
 * @author Mandal Kartik
 * @version 1.0
 * @since   2015-07-08
 */
public class SocketServerExample {
    
    //static ServerSocket variable
    private static ServerSocket server;
    //socket server port on which it will listen
    private static int port = 9876;
    
    public static void main(String args[]) throws IOException, ClassNotFoundException{
        //create the socket server object
        server = new ServerSocket(port);
        //keep listens indefinitely until receives 'exit' call or program terminates
        while(true){
            System.out.println("Waiting for client request");
            //creating socket and waiting for client connection
            Socket socket = server.accept();
            //read from socket to ObjectInputStream object
            ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
            //convert ObjectInputStream object to String
            String message = (String) objectInputStream.readObject();
            System.out.println("Message Received: " + message);
            File file=new File(message);
            //create ObjectOutputStream object
            ObjectOutputStream objectOutPutStream = new ObjectOutputStream(socket.getOutputStream());
            if(file.exists()){
            FileReader fileReader = new FileReader(message);
            BufferedReader bufferReader = new BufferedReader(fileReader);
            //write object to Socket
            String line;
            StringBuffer stringBuffer=new StringBuffer();
            while((line = bufferReader.readLine()) != null) {
            System.out.println(line);
            stringBuffer.append(line);
            stringBuffer.append(System.getProperty("line.separator"));
            }
            objectOutPutStream.writeObject(stringBuffer.toString());
            fileReader.close();
          
            //close resources
            objectInputStream.close();
            objectOutPutStream.close();
            socket.close();
            }else{
             System.out.println("File is not here");
              objectOutPutStream.writeObject("File is not there");
              objectOutPutStream.close();
                 socket.close();
            }
            //terminate the server if client sends exit request
            if(message.equalsIgnoreCase("exit")) break;
        }
        System.out.println("Shutting down Socket server!!");
        //close the ServerSocket object
        server.close();
    }
    
}



Step 2> Run in Different Server of SocketClientExample

A>
package com.kartik.socket;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.Properties;
import java.util.Scanner;
/**
 * This class implements java socket client
 * @author MandalKC
 *
 */
public class SocketClientExample {

 public static void main(String[] args) throws UnknownHostException,
   ClassNotFoundException, IOException, InterruptedException {
  SocketClientImplement socketClientImplement = new SocketClientImplement();
  String domainName = null;
  int portNumberOfServer = 0;
  Properties prop=new Properties();
  InputStream input= null;
  String fileName = null;
  String fileNameWithPath = null;
  /**
   * This is read properties file of Hard code data of local or remote syetem
   */
  /*try{
   input= new FileInputStream("D:\\WorkSpace\\clientserver\\SocketClient\\src\\com\\kartik\\socket\\configure.properties");
   //getClass().getClassLoader().getResourceAsStream("configure.properties");//
   prop.load(input);
    fileName = prop.getProperty("fileName");
    fileNameWithPath=prop.getProperty("filePath");
  }catch(IOException e){
   e.printStackTrace();
  }*/
  /**
   * This is hard code data of local system
   */
  /* fileName = "design.txt";
   fileNameWithPath = "D:\\";*/
  /**
   * Hard code data of file name and file path of remote system
   */
  /* fileName = "xyz.dat";
   fileNameWithPath = "\\\\IN-SAMALRAR-1\\\\data\\\\XA\\\\cfd\\\\ssim\\";*/

  /**
   * Console read for file name and file path
   */
System.out.println("First File name space file path please enter");
  Scanner console = new Scanner(System.in);
     while (console.hasNext()) {
      fileName=console.next();
      System.out.println("fileName--->>>>"+fileName);
      fileNameWithPath=console.next();
      System.out.println("fileNameWithPath--->>>>"+fileNameWithPath);
      break;
     }
  socketClientImplement.callSocketServer(domainName, portNumberOfServer,fileName, fileNameWithPath);
 }
}

B>

package com.kartik.socket;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* <h1>Socket Client Implement!</h1>
* The SocketClientImplement program implements an application that
* simply displays call to Socket Server to the standard output.
* <p>
*
* @author  Mandal Kartik
* @version 1.0
* @since   2015-07-08
*/
public class SocketClientImplement {
 /**
  * callSocketServer method use for Socket server call
  * @param domainName
  *            domainName like as www.google.com
  * @param portNumberOfServer
  *            port number of socket server by default like 9876
  * @param fileName
  *            fileName
  * @param fileNameWithPath
  *            fileNameWithPath
  * @throws UnknownHostException
  *             UnknownHostException
  * @throws IOException
  *             IOException
  * @throws ClassNotFoundException
  *             ClassNotFoundException
  * @throws InterruptedException
  *             InterruptedException
  */
 @SuppressWarnings("resource")
 public void callSocketServer(String domainName, int portNumberOfServer,
   String fileName, String filePath)
   throws UnknownHostException, IOException, ClassNotFoundException,
   InterruptedException {
  InetAddress host = null;
  //get the localhost IP address, if server is running on some other IP, you need to use that
  host = (null != domainName) ? InetAddress.getByName(domainName)
    : InetAddress.getLocalHost();
  int port = 0;
  //get the server socket address port number
  port = (portNumberOfServer > 0) ? portNumberOfServer : 9876;
  String relPathWithFileName = null;
  //get the file path
  relPathWithFileName=filePathMethod(fileName,filePath);
  System.out.println("Please read copy that path and access this path if it is remote file path access is there or not");
  System.out.println(relPathWithFileName);
  Socket socket = null;
  ObjectOutputStream objectOutputStream = null;
  ObjectInputStream objectInputStream = null;
  // establish socket connection to server
  socket = new Socket(host.getHostName(), port);
  // write to socket using ObjectOutputStream
  objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
  System.out.println("Sending request to Socket Server");
  objectOutputStream.writeObject(relPathWithFileName);
  // read the server response message
  objectInputStream = new ObjectInputStream(socket.getInputStream());
  String message = (String) objectInputStream.readObject();
  System.out.println("Message: " + message);
  // close resources
  objectInputStream.close();
  objectOutputStream.close();
  Thread.sleep(100);
 }
 /**
  * This is find out the absoluteFilePath of a file for any server
  * @param fileName
  *            fileName
  * @param pathName
  *            pathName
  * @return absoluteFilePath
  */
 public String filePathMethod(String fileName, String pathName) {
  String absoluteFilePath = "";
  //String workingDir = System.getProperty("user.dir");
  String workingDir= pathName;
  //String absoluteFilePath = "";
  String runnigServerOs = System.getProperty("os.name").toLowerCase();
  if (runnigServerOs.indexOf("win") >= 0) {
   // if windows
   absoluteFilePath = workingDir + "\\" + fileName;
  } else if (runnigServerOs.indexOf("nix") >= 0
    || runnigServerOs.indexOf("nux") >= 0
    || runnigServerOs.indexOf("mac") >= 0) {
   // if unix or mac
   absoluteFilePath = workingDir + "/" + fileName;
  } else {
   // unknow os?
   absoluteFilePath = workingDir + "/" + fileName;
  }
  System.out.println("Final filepath : " + absoluteFilePath);
  return absoluteFilePath;
 }
}
Previous
Next Post »