0

I'm trying to copy a file from Client to Server, in Java, like so:

Client:

public class Client {

    public static void main(String[] args) throws Exception {
        String fileName = "D:\\6282.mp3";

        try {

        } catch (Exception e) {
            Scanner scanner = new Scanner(System.in);
            String file_name = fileName;

            File file = new File(file_name);
            Socket socket = new Socket("localhost", 3332);
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());

            oos.writeObject(file.getName());

            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[Server.BUFFER_SIZE];
            Integer bytesRead = 0;

            while ((bytesRead = fis.read(buffer)) > 0) {
                oos.writeObject(bytesRead);
                oos.writeObject(Arrays.copyOf(buffer, buffer.length));
            }

            oos.close();
            ois.close();
            System.exit(0);
        }

    }

}

Server:

public class Server extends Thread {

    public static final int PORT = 3332;
    public static final int BUFFER_SIZE = 626;

    @Override
    public void run() {
        try {
            ServerSocket serverSocket = new ServerSocket(PORT);

            while (true) {
                Socket s = serverSocket.accept();
                saveFile(s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveFile(Socket socket) throws Exception {
        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
        FileOutputStream fos = null;
        byte[] buffer = new byte[BUFFER_SIZE];

        // 1. Read file name.  
        Object o = ois.readObject();

        if (o instanceof String) {
            fos = new FileOutputStream(o.toString());
        } else {
            throwException("Something is wrong");
        }

        // 2. Read file to the end.  
        Integer bytesRead = 0;

        do {
            o = ois.readObject();

            if (!(o instanceof Integer)) {
                throwException("Something is wrong");
            }

            bytesRead = (Integer) o;

            o = ois.readObject();

            if (!(o instanceof byte[])) {
                throwException("Something is wrong");
            }

            buffer = (byte[]) o;

            // 3. Write data to output file.  
            fos.write(buffer, 0, bytesRead);

        } while (bytesRead == BUFFER_SIZE);

        System.out.println("File transfer success");

        fos.close();

        ois.close();
        oos.close();
    }

    public static void throwException(String message) throws Exception {
        throw new Exception(message);
    }

    public static void main(String[] args) {
        new Server().start();
    }
}

When I run I get:

run:
BUILD SUCCESSFUL (total time: 0 seconds)

but nothing really happens. This is my first at Client-Server and I'm not sure what I'm getting wrong.

Please help. Thank you.

ILikeProgramming
  • 293
  • 3
  • 8
  • 23
  • 2
    Are you sure your client file is correct? the try block doing nothing seems fishy to me. – Mc Kevin Mar 07 '14 at 09:22
  • I've tried different files but nothing happens. Or where does the file get saved? I've looked at localhost, the project file, but nothing – ILikeProgramming Mar 07 '14 at 09:24
  • "I'm trying to copy a file from Client to Server", What does this line means? are you trying to get the data from "D:\\6282.mp3" and prints the output on the Server console? – Mc Kevin Mar 07 '14 at 09:28
  • I'd like the file, D:\\6282.mp3, to be copied onto the server, localhost, or just anywhere else, for a start – ILikeProgramming Mar 07 '14 at 09:30
  • 1
    You'll need a destination file path specified. – Mc Kevin Mar 07 '14 at 09:31
  • Thanks [@Mc Kevin](http://stackoverflow.com/users/2715233/mc-kevin). Would you mind helping pointing out how to go about that, specifying the "destination file path" – ILikeProgramming Mar 07 '14 at 09:34
  • 1
    http://stackoverflow.com/questions/2885173/java-how-to-create-and-write-to-a-file refer this on how to implement the writing to destination file on server side. Divide and conquer, before that u must: 1st, make sure you can read every line of your client file. 2nd, make sure you can send the information to Server – Mc Kevin Mar 07 '14 at 09:36
  • Why doesnt the try block have any code? Try adding the code inside try block. – Sandeep Mar 07 '14 at 09:40
  • Why use `Object*Stream`s? They are only used for serialization or deserialization purposes, and you seem to want to copy an MP3... – fge Mar 07 '14 at 09:41

1 Answers1

1

Some issues in your code are:

For the client ,you have written the entire code in the catch block, which will not work unless an exception occurs.

You are trying to pass the name of the file here instead of the file.

oos.writeObject(file.getName());

You need to run the server, then the client. here is a sample working code:

Client:

public class Client {

    public static void main(String[] args) throws Exception {
        String fileName = "C:\\2048.jpg";

        try {
            File file = new File(fileName);
            Socket socket = new Socket("localhost", 3332);
            byte[] mybytearray = new byte[(int) file.length()];
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            bis.read(mybytearray, 0, mybytearray.length);
            OutputStream os = socket.getOutputStream();
            os.write(mybytearray, 0, mybytearray.length);
            os.flush();
            os.close();
        } catch (Exception e) {
        }

    }
}

Server:

public class Server extends Thread {

    public static final int PORT = 3332;
    public static final int BUFFER_SIZE = 626;

    @Override
    public void run() {
        try {
            ServerSocket serverSocket = new ServerSocket(PORT);
            while (true) {
                Socket s = serverSocket.accept();
                saveFile(s);
            }
        } catch (Exception e) {
        }
    }

    private void saveFile(Socket socket) throws Exception {
        InputStream ois = socket.getInputStream();
        FileOutputStream fos = new FileOutputStream("C:\\2049.jpg");;

        byte[] mybytearray = new byte[1024];
        System.out.println("Reading file from server...");
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        int bytesRead;
        while ((bytesRead = ois.read(mybytearray)) != -1) {
            bos.write(mybytearray);
        }

        bos.close();
        System.out.println("Writing file complete...");

    }

    public static void main(String[] args) {
        new Server().start();
    }
}
Sandeep
  • 712
  • 1
  • 10
  • 22
  • Thanks [@Sandeep](http://stackoverflow.com/users/2281800/sandeep) for the response. I tried out your code as is, only changing the name of the `jpg` file. Even used the destinations, but still nothing. I only get `run: BUILD SUCCESSFUL (total time: 2 seconds)`. What might I be doing wrong? Please help. – ILikeProgramming Mar 07 '14 at 12:36
  • @user3189827 Hi, you have to run the server first, then the client. Since the server is a thread it will stay running till you stop it, and all the files you send will be written to the directory you provide(like "C:\\2049.jpg") . If you are running it on the terminal (cmd) you might need to run both on saperate terminals – Sandeep Mar 10 '14 at 04:24