Open In App

SimpleFileServer in Java

Last Updated : 11 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A server is a computer that is dedicated solely to the purpose of serving. It serves files to its clients whenever requests are made, and it should always be available. A program running on a port within the server is used to handle requests. The term ‘server’ can refer to a physical or virtual computer system (hardware), a program running inside the physical machine, or a virtual machine inside the physical machine. Servers can have databases or can be connected to other servers that have databases. A socket is an endpoint for communication between two computer machines over a network. A socket is a combination of a port number and an IP address, which is used to uniquely identify a specific process running on a specific computer. A process running on a server is communicating with a process running on a client computer and we have to identify both, the process as well as the computer so that we can request or send files to the right process of the right computer. Socket programming is used to establish communication between two processes that are running on different computers over a network. It is used to develop client-server applications. Socket programming can be implemented in various programming languages like Java, C++, Python, and so on.

Implementation

In the implementation, we have a client-side and a server side. The client side is used to make requests for uploading or downloading a file. The server side is used to handle two types of requests: one is for downloading a file, and the other is for uploading a file to the server.

Client-side

Java




import java.io.*;
import java.net.Socket;
import java.util.Scanner;
 
public class ClientSide {
    public static void main(String[] args) throws Exception
    {
        System.out.println("Client");
        int port = 2500,
            choice; // port number and choice variable for
                    // taking user choice for downloading or
                    // uploading a file.....
        String ip
            = "localhost"; // Server IP address.....send or
                           // receive file from this
                           // IP.....IP is used for making
                           // connection.....
 
        while (true) {
            Socket clientSocket = new Socket(
                ip, port); // Socket object used for making
                           // a connection to the given IP
                           // and Port address.....
            Scanner sc = new Scanner(System.in);
 
            System.out.println(
                "Enter Your Choice - 1 For Sending File and 2 For Downloading File : ");
 
            choice = sc.nextInt(); // taking choice from
                                   // console.....
            sendReq(
                choice,
                clientSocket); // method is used for sending
                               // the request to the
                               // server.....check the
                               // sendFile and receiveFile
                               // methods also which are
                               // inside sendReq
        }
    }
 
    public static void sendReq(int choice,
                               Socket clientSocket)
        throws Exception
    {
        if (choice == 1) // choice 1 is for sending a file
                         // to server.....uploading....
        {
            sendFile(
                clientSocket); // sends a file to
                               // server....it takes
                               // fileName and fileContent
                               // from the console.....and
                               // sends it to server.....
        }
        else if (choice
                 == 2) // choice 2 is for receiving a file
                       // from server....downloading...
        {
            receiveFile(
                clientSocket); // receive a file from server
                               // and stores it into a given
                               // directory or a folder.....
        }
        else {
            System.out.println("Invalid Choice");
        }
    }
 
    // used for send the file..........
    public static void sendFile(Socket clientSocket)
    {
 
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter file Name : ");
        String name = sc.nextLine(); // asking for file name
                                     // from console.....
        System.out.println("Enter Content : ");
        String content
            = sc.nextLine(); // asking for content of the
                             // file....
        Data data = new Data(
            1, name,
            content); // Data class object is used for
                      // making the given data into
                      // serializable......read more about
                      // serializable on internet.....
        ObjectOutputStream
            outputStream; // Using an ObjectOutputStream,
                          // you can write both primitive
                          // data types and graphs of Java
                          // objects to an OutputStream.
        try {
            outputStream = new ObjectOutputStream(
                clientSocket.getOutputStream());
            outputStream.writeObject(
                data); // writeObject(Object obj) method
                       // writes the specified object to the
                       // ObjectOutputStream.....
            System.out.println("File Sent Successfully!!");
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println("Something Went Wrong");
            e.printStackTrace();
        }
    }
 
    // used for receiving the file.......
    public static void receiveFile(Socket clientSocket)
        throws Exception
    {
        ObjectOutputStream outputStream
            = new ObjectOutputStream(
                clientSocket.getOutputStream());
        ObjectInputStream inputStream
            = new ObjectInputStream(
                clientSocket.getInputStream());
        Scanner sc = new Scanner(System.in);
 
        System.out.println("Enter file Name : ");
        String name
            = sc.nextLine(); // asking for file name that
                             // user want to download....
 
        Data data = new Data(
            2, name,
            ""); // making data object with given info....
        // sending info
        outputStream.writeObject(data);
 
        // receiving file
        Data receivedData
            = (Data)inputStream
                  .readObject(); // getting data from input
                                 // stream in the form of
                                 // Data object.....
 
        // storing file to the given directory or folder
        // with the given file name......
        File fileToBeDownloaded = new File(
            "C:\\Users\\Manish Sharma\\Documents\\Java File Server\\Client Downloaded Files\\"
            + receivedData.fileName);
        FileOutputStream fileOutputStream
            = new FileOutputStream(fileToBeDownloaded);
        fileOutputStream.write(
            (receivedData.fileContent).getBytes());
    }
}


Server-side

Java




import java.io.*;
import java.net.*;
 
public class ServerSide {
    static int port = 2500; // port address....
    public static void main(String[] args) throws Exception
    {
        System.out.println("Server");
        ServerSocket serverSocketObj = new ServerSocket(
            port); // server serving at port =
                   // 2500......ServerSocket starts this
                   // program to port = 2500....
        while (true) // infinite loop so that server is
                     // always listening to requests.....
        {
            receivingRequest(
                serverSocketObj); // handling requests.....
        }
    }
 
    // handling requests....downloading and uploading....
    public static void
    receivingRequest(ServerSocket serverSocketObj)
        throws Exception
    {
        Socket serverSideSocket = serverSocketObj.accept();
        ObjectOutputStream outputStream
            = new ObjectOutputStream(
                serverSideSocket
                    .getOutputStream()); // output
                                         // stream....
        ObjectInputStream inputStream
            = new ObjectInputStream(
                serverSideSocket
                    .getInputStream()); // input stream....
 
        Data data = (Data)inputStream.readObject();
        if (data.choice == 1) {
            // Receive file
            receiveFile(
                data, inputStream); // receiving a file.....
        }
        else {
            sendFile(data,
                     outputStream); // sending a file....
        }
    }
 
    // receiving the file from client and store it.....
    public static void
    receiveFile(Data data, ObjectInputStream inputStream)
        throws Exception
    {
        String fileName
            = data.fileName; // getting file name....
        String fileContent
            = data.fileContent; // getting file content....
 
        File newFile = new File(
            "C:\\Users\\Manish Sharma\\Documents\\Java File Server\\Server Files\\"
            + fileName); // file object.....
        FileOutputStream fileOutputStream
            = new FileOutputStream(newFile);
 
        fileOutputStream.write(
            fileContent
                .getBytes()); // writing the file to the
                              // given directory or folder
                              // with the given name......
    }
 
    // sends the file to the client.....
    public static void
    sendFile(Data data, ObjectOutputStream outputStream)
        throws Exception
    {
        File file = new File(
            "C:\\Users\\Manish Sharma\\Documents\\Java File Server\\Server Files\\"
            + data.fileName); // getting the file from the
                              // server's directory or
                              // folder (from server
                              // storage)......
        if (file.exists()
            == true) // if given file name is exits in
                     // server storage....
        {
            byte[] fileContentInBytes = new byte[(
                int)(file.length())]; // creating an array
                                      // of bytes to storing
                                      // the file
                                      // content....
            FileInputStream fileInpStream
                = new FileInputStream(file);
            fileInpStream.read(
                fileContentInBytes); // reading the file
                                     // from input stream
                                     // (input stream
                                     // between File System
                                     // of server and this
                                     // program) and storing
                                     // it into byte
                                     // array....
 
            Data fileToSend = new Data(
                0, data.fileName,
                new String(
                    fileContentInBytes)); // creating Data
                                          // object which
                                          // contains info
                                          // about file
                                          // which have to
                                          // send....
 
            outputStream.writeObject(
                fileToSend); // sending object to client
        }
        else {
            System.out.println("File Not Exist");
        }
    }
}


Data Class (This file is used in the above files)

Java




import java.io.Serializable;
 
public class Data implements Serializable {
    private static final long serialVersionUID = 1L;
    public int choice; // choice variable
    public String fileName; // file name variable.....stores
                            // file name....
    public String
        fileContent; // file content variable.....stores
                     // file content....
 
    Data(int choice, String fileName,
         String fileContent) // constructor.....
    {
        this.choice = choice;
        this.fileName = fileName;
        this.fileContent = fileContent;
    }
}


Output: 

1. Uploading to the server:

Given file name and file content will stored inside the server storage directory or folder.

Given file name and file content will stored inside the server storage directory or folder.

 

File is stored inside the server's storage directory or folder.

File is stored inside the server’s storage directory or folder.

2. Downloading a file:

Given file will be downloaded.

Given file will be downloaded.

File is downloaded inside the client's storage.

File is downloaded inside the client’s storage.

Folder Structure

Folder or directory Structure

Folder or directory Structure.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads