views:

549

answers:

2

I have created server program which will send an image file to the client. My program works fine if the image is of 512 byte. But it does nit work fine for large file.

In this case i am not getting the exact image that i am supposed to get. means my recovered image is in some improper manner. So how to solve this problem

I am using java socket channel and java nio in server while simple socket in client side.

Thanks Sunil

+1  A: 

Here's your bug:

while(fileChannel.read(buffer)>0)

The read() method will not necessarily fill the buffer; it will read an arbitrary number of bytes and return that number. You have to allow for the case that it reads less than the buffer's capacity and write only that many bytes, which is also necessary since the file size is not necessarily a multiple of your buffer size and the last read will almost never exactly fill the buffer.

The same is true on the client side - available() is not useful here, you have to simply read and then deal with however many bytes you got.

Michael Borgwardt
A: 

I don't see you flushing and closing your output stream on the client side. When you break out you should close() the output stream, and any cached data will be written out to the file.

Brian Agnew