This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to safe send file?

 
Joe Blant
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i send file using tcp socket on LAN.
i want to send all file both ascii and binary files.
some time i send safely, sometime it corrupts in transit.
mostly when i send very small file, it corrupts.


Are there any ways to send safely?
with regards,
kaze

in SenderThread...

FileInputStream fin;
Socket socket = ...
OutputStream netout = socket.getOutputStream();

final int SIZE = 8192;
byte [] data = new byte[SIZE];
int bytesRead = 0;
long bytesSend = 0;
while(( bytesRead = fin.read(data)) != -1) {

while(bytesRead < SIZE) {

int i = fin.read(data, bytesRead, SIZE-bytesRead);
if(i == -1 ) break;
bytesRead += i;
}
netout.write(data,0,bytesRead);
netout.flush();
bytesSend += bytesRead;
}//end outer while


===================================================
in ReceiverThread...

Socket socket =...
InputStream netIn = socket.getInputStream();
FileOutputStream fout =...

final int SIZE = 8192;
byte [] data = new byte[SIZE];
int bytesRead = 0;
long bytesReceive = 0;

while(( bytesRead = netIn.read(data)) != -1) {

while(bytesRead < SIZE ) {
int i = netIn.read(data, bytesRead, SIZE - bytesRead);
if(i == -1 ) break;
bytesRead += i;
}
fout.write(data,0 , bytesRead);
fout.flush();
}
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, welcome to the ranch! I have to admit I don't see where this goes wrong, but I would suggest trimming it down a bit. This is simpler and works with files larger than one buffer full:

See if that does the same thing and maybe helps with the problem.
 
Edwin Dalorzo
Ranch Hand
Posts: 961
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
At first sight it appears nothing is wrong with your reading process. Could you post the code you are using to write the file into the Socket OutputStream?. Maybe the problem is in the writing and not in the reading of the file.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic