wood burning stoves 2.0*
The moose likes Sockets and Internet Protocols and the fly likes how to safe send file? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Sockets and Internet Protocols
Bookmark "how to safe send file?" Watch "how to safe send file?" New topic
Author

how to safe send file?

Joe Blant
Greenhorn

Joined: Mar 11, 2006
Posts: 11
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

Joined: Jan 29, 2003
Posts: 8791
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.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Edwin Dalorzo
Ranch Hand

Joined: Dec 31, 2004
Posts: 961
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: how to safe send file?