4

I am trying to transfer a binary file from the server to the client by blocks of bytes at a time. However, I am having a issue where it is stuck at transfering 8kb. The file is usually greater than a 1mb and the byte array is of size 1024. I believe it has to do something with my while loop since it doesnt close my connection. Any help? Thanks

Client

import java.io.*;
import java.net.Socket;

public class FileClient {

    public static void main(String[] argv) throws IOException {
        Socket sock = new Socket("localhost", 4444);
        InputStream is = null;
        FileOutputStream fos = null;

        byte[] mybytearray = new byte[1024];
        try {
            is = sock.getInputStream();
            fos = new FileOutputStream("myfile.pdf");

            int count;
            while ((count = is.read(mybytearray)) >= 0) {
                fos.write(mybytearray, 0, count);
            }
        } finally {
            fos.close();
            is.close();
            sock.close();
        }
    }
}

Server

import java.net.*;
import java.io.*;

public class FileServer {

    public static void main(String[] args) throws IOException {
        ServerSocket servsock = new ServerSocket(4444);
        File myFile = new File("myfile.pdf");
        FileInputStream fis = null;
        OutputStream os = null;
        while (true) {
            Socket sock = servsock.accept();
            try {
            byte[] mybytearray = new byte[1024];
            fis = new FileInputStream(myFile);
            os = sock.getOutputStream();

            int count;
            while ((count = fis.read(mybytearray)) >= 0) {
                os.write(mybytearray, 0, count);

            }
            os.flush();
            } finally {
            fis.close();
            os.close();
            sock.close();

            System.out.println("Socket closed");
            }
        }
    }
}

1 Answer 1

3

Your loops should check for count >= 0 rather than count > 0, and the streams and the socket should be closed in a finally block. Other than that, the code looks fine to me.

What do you mean by "it is stuck at transfering 8kb"? Any exception occurring?

Sign up to request clarification or add additional context in comments.

2 Comments

I've changed the count and added a finally block but problem still exist. What I meant by stuck is that it doesnt reach the finally block. it copies and write only ~8kb of data and it just stalls
The finally block should be out of the while loop. And you should make sure that each stream is closed by catching the IOException thrown by the close call itself. Which one stalls? the client or the server?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.