Search code examples
javanetwork-programmingbroken-pipe

java network-broken pipe and received file corrupted


I am trying to write a server that accepts files and write it in certain directory using DataInputStream and BufferedInputStream.

The server gets 'user name(string)' 'number of files(int)' 'file name(string)' 'size of each file(long)' and 'contents of file which is uninterpreted bytes(byte[])'

and if everything is successful then, I am supposed to send boolean value.

But the problem is that it is not receiving file correctly.

From time to time I get 'broken pipe' error message or the file is corrupted after I receive.

Fixed the problem..


Solution

  • One small thing which may be related to your problem. You should be decrementing your file size variable by the number of bytes actually read, instead of the number of bytes requested to be read:

           while(fileSize>0){
                if(fileSize < byteSize)
                    byteSize = (int)fileSize;
                int byteRead = din.read(b, 0, byteSize);
                fos.write(b);
                fileSize -= byteRead; // <-- See here
            }