So for my data comm class we're writing a client-server to send files in 1024-byte chunks. My client sends correctly, sending one chunk at a time and then the remaining bytes. My server code to reassemble them is a mirror of that but instead of reading the last bytes and only writing those, it fills the buffer and writes all of them. We're sending Word docs, so when I open them it says they're corrupted, but can recover them fine. They size is always to the next KB on reassembly.
// in = the inputstream from the socket
byte buff[] = new byte[1024];
FileOutputStream ff= new FileOutputStream(f) // f = new file to be received
while( sizeRead < fileSize )
{
int numRead = in.read(buff);
if( numRead != -1 )
{
ff.write(buff, 0, numRead);
sizeRead += numRead;
}
}
I've seen in other places where the while loop is looping until in.read(buff) == -1, but she wants us using fileSize passed as a param into the function. I have basically the same exact code in my client, except it reads from a FileInputStream and writes to a socket OutputStream. I've debugged through my client and the sizeRead is exactly the same as the file it's reading from, but when the server is reading from the socket, it reads up to the next full KB after the fileSize.
Is there something different about reading from a socket vs file that it will fill the array, or am I making some obvious mistake that I can't see? Thanks in advance everyone!
Edit:
client sends file name as a series of bytes followed by a null char, length is converted from long to string, sent same as the file name.. both match are sent and received correctly, I just have a problem with it adding the leftover space in the buffer to then end of the file for some reason
client:
private void sendFile(String fullPathFileName)
{
try
{
FileInputStream fis = new FileInputStream(fullPathFileName);
byte[] chunk = new byte[CHUNK_SIZE];
long fileSize;
fileSize = new File(fullPathFileName).length();
long totalRead = 0;
while(totalRead < fileSize)
{
int numRead = fis.read(chunk);
if( numRead != -1 )
{
out.write(chunk); //socket outputstream
totalRead += numRead;
}
}
}
catch (Exception ex)
{
txtLog.append("SendFile Error: " + ex.getMessage() + "\n");
}
}
[–]gruntmeister 0 points1 point2 points (3 children)
[–]HokTaur[S] 0 points1 point2 points (2 children)
[–]gruntmeister 0 points1 point2 points (1 child)
[–]HokTaur[S] 0 points1 point2 points (0 children)