-1

I am trying to read data from the server in file size of 100 Kb. So I have broken the data and sent 6 files. I can see at the server that the file is properly broken in 5 chunks of 100 kb and the remaining on of 74 kb or so. At the client side I am trying to receive these 6 files so I have kept the buffer size to be 100 but I am getting 7 files. here is the part of my code

try {
        sock = new Socket(server, port);
        System.out.println("Connecting...");
        int buffer = 100 * 1000, bytesRead = 0, counter = 0;

        // receive file
        BufferedInputStream bis = new BufferedInputStream(sock.getInputStream(), buffer);
        byte[] mybytearray = new byte[buffer];
        while ((bytesRead = bis.read(mybytearray))!=-1) {
                String fileName = "C:/Users/Desktop/Client2/" + counter;
                File newFile = new File(fileName);
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFile));
                bos.write(mybytearray, 0, bytesRead);
                bos.flush();
                bos.close();

                System.out.println("File " + counter + " downloaded (" + bytesRead + " bytes read)");
            counter++;
        }

    }

The result I am getting is this.

File 0 downloaded (35040 bytes read)
File 1 downloaded (100000 bytes read)
File 2 downloaded (100000 bytes read)
File 3 downloaded (100000 bytes read)
File 4 downloaded (100000 bytes read)
File 5 downloaded (100000 bytes read)
File 6 downloaded (39346 bytes read)

What wrong am I doing?

arnav bhartiya
  • 303
  • 1
  • 3
  • 9

1 Answers1

0

socket not reading according to the buffer size

Where does it say that it should? From the Javadoc:

Reads up to [my emphasis] len bytes of data from the input stream into an array of bytes.

The correct way to send multiple files over a single connection is given here.

Community
  • 1
  • 1
user207421
  • 305,947
  • 44
  • 307
  • 483