Trouble sending files over the network.

I have a network application that corrupts any files that it sends, although the received file is very close (but never exact) to the number of bytes it should be. There is a socket client that each client has, and the Packet data structure is searializable and simply contains a string message and the byte[]. Am I doing something wrong?

Here is my code for Sending:

ObjectOutputStream toOtherClient =new ObjectOutputStream(client.getOutputStream());

ObjectInputStream fromOtherClient =new ObjectInputStream(client.getInputStream());

Packet fileRequest = (Packet)fromOtherClient.readObject();

File file =new File(DefaultConfig.defaultFileDirectory+"\\"+fileRequest.getMessage());

FileInputStream fromDisk =new FileInputStream(file);

BufferedInputStream fromDiskBuffered =new BufferedInputStream(fromDisk);

byte[] buffer =newbyte[maxPayload];

while(fromDiskBuffered.available() > 0)

{

if (fromDisk.available() > maxPayload)

{

fromDiskBuffered.read(buffer);

toOtherClient.writeObject(new Packet(Packet.Command.File,"",buffer));

}

else

{

buffer =newbyte[fromDiskBuffered.available()];

fromDiskBuffered.read(buffer);

toOtherClient.writeObject(new Packet(Packet.Command.File,"",buffer));

}

}

fromDiskBuffered.close();

fromDisk.close();

toOtherClient.writeObject(new Packet(Packet.Command.File,"ack"));

fromOtherClient.close();

toOtherClient.close();

client.close();

Here is my code for recieving:

Socket client =new Socket(host, Integer.parseInt(port));

ObjectOutputStream toOtherClient =new ObjectOutputStream(client.getOutputStream());

ObjectInputStream fromOtherClient =new ObjectInputStream(client.getInputStream());

FileOutputStream toDisk =new FileOutputStream(DefaultConfig.defaultFileDirectory+"//"+whatFile); BufferedOutputStream toDiskBuffered =new BufferedOutputStream(toDisk);

toOtherClient.writeObject(new Packet(Packet.Command.File,whatFile));

Packet incoming;

while(true)

{

incoming = (Packet)fromOtherClient.readObject();

if (incoming.getMessage().equals("ack"))

{

break;

}

byte[] fileData = (byte[])incoming.getData();

toDiskBuffered.write(fileData);

}

toDiskBuffered.flush();

toDiskBuffered.close();

toDisk.close();

fromOtherClient.close();

toOtherClient.close();

client.close();

[3866 byte] By [ryanbgstla] at [2007-11-27 4:44:08]
# 1

You're assuming that available() gives you the total length of the file, which it doesn't, and you're ignoring the result returned by the read call, so you're assuming you've read data you may not have read.

I would rethink the tactic of reading the entire file into a single buffer - this doesn't scale. It's only safe if you know that the file size has an upper bound and that this is relatively low.

ejpa at 2007-7-12 9:56:01 > top of Java-index,Java Essentials,Java Programming...