I will try to break down my problem and explain what is going on as it is impossible to post my whole code here (thousands of lines).
I am implementing a client/server application and I am trying to send a file over a socket (SSLSocket
). I have written below a block of my code.
The problem occurs when trying to send large files (trying to send a 100MB pdf). When I am sending txt files only a few kb long everything works great. As soon as I try to send a larger file it all falls apart. And by that I mean: the client stalls at the line where it is sending the file bytes[] and the server gets only part of the (starting) file bytes and ignores the rest continuing the execution. For example if the client sends the bytes [1,2,3,4,5,...,6,7,8,9,10]
the server will get something like [1,2,3,4,5,...,0,0,0,0,0]
(it is not actually receiving 0s after a point but as it is initialised with the correct size the initialised bytes stay to the starting value).
client
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
dos.write(largeByteArray);
dos.flush();
server
DataInputStream dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
dest = new byte[(int) sizeOfFileReceived];
dis.read(dest);
My guess was that the server fails to ACK the client because it is trying to receive all the bytes in one go and this is where it all falls apart.
I tried to change the code on the receiving side to get chunks of bytes (8000bytes) and then concatenate them into a single array but didn't work out well (might be a fault of my implementation though). I used the following posts to get ideas but might have done it wrong: here and here
Any ideas on what is going on?
EDIT: What i tried was something like this:
byte[] buf = new byte[8000];
int bytesRead;
int pos = 0;
while ((bytesRead = dis.read(buf, 0, buf.length)) != -1) {
System.arraycopy(dest, pos, buf, 0, bytesRead);
pos += bytesRead;
}
UPDATE: when using the code of the last edit the problem is that in the last call of the dis.read(buf, 0, buf.length)
it completely stalls with no exception without returning any result instead of -1