我在服务器端,并从客户端接收图像作为二进制流,服务器检测到我们处理图像并且字节大小通过来自客户端的先前消息到达服务器!
服务器有一个应该读取的文件大小,并且流...Eter到while循环...从客户端流中读取,并立即写入文件,并重置缓冲区以读取
一切正常工作直到几千字节之前文件末尾有几千字节没有写入文件...我在服务器库上得到较小的文件...(我可以看到底部带有灰色小行的图像。
这是我的尝试:
/*loop*/ while (bytesRemaining!=0) {
try {
// read from client
baos = new ByteArrayOutputStream();
bytesRemaining = sizeToread - readtotal;
bytesRead = OIS.read(aByte, 0, bytesRemaining);
readtotal+=bytesRead;
System.out.println( ", Remaining: " +bytesRemaining);
System.out.println("read at oce: "+bytesRead) ;
System.out.println(++i+") have Read: "+ readtotal+", aByte:"+aByte[i-1]);
try {
baos.write(aByte); // write first byte to buffer
try{
bos.write(baos.toByteArray(),0,bytesRead);
}catch (IOException s){ System.out.println("not write to file"+s);}
baos.reset();
// bos.flush();
} catch (IOException ex) {
Logger.getLogger(ThrdConv.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("baos.write(aByte); error = "+ex );
}
// if (!(OIS.available()> 0))break; // until uavailabil stream
} catch (EOFException eoff) {
Logger.getLogger(ThrdConv.class.getName()).log(Level.SEVERE, null, eoff);
System.out.println("Line 601 error= "+eoff );
break;
} catch (IOException ex) {
Logger.getLogger(ThrdConv.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Line 612,613 error= "+ex );
}
} //loop End ///////////////////////////////////////////
注意:文件大小:474591
我的印刷品给出:
...
...
...
458) have Read: 468992, aByte:52
, Remaining: 5599
read at oce: 1024
459) have Read: 470016, aByte:59
, Remaining: 4575
read at oce: 1024
460) have Read: 471040, aByte:-117
, Remaining: 3551
read at oce: 1024
461) have Read: 472064, aByte:-110
, Remaining: 2527
read at oce: 1024
462) have Read: 473088, aByte:-8
, Remaining: 1503
read at oce: 1024
463) have Read: 474112, aByte:-124
, Remaining: 479
read at oce: 479
464) have Read: 474591, aByte:125
, Remaining: 0
read at oce: 0
465) have Read: 474591, aByte:30
realfile: C:\wamp\www\RandomSendServer\images\1384252358431.jpg
have Read: 474591 !!!
URL sent Back
我得到大小为 466944 的文件,而不是: 474591 .... 任何帮助
更新
according to answer 1 I make this change... my loop now looks:
while ((bytesRead = OIS.read(aByte))>1)
{ bos.write(aByte,0,bytesRead);
i+=bytesRead;
System.out.println(bytesRead+" "+i);
}
印刷品:
总阅读量:474591 真实文件:C:\wamp\www\RandomSendServer\images\1384262866220.jpg 发送的 URL
但是同样的问题仍然 是循环告诉它读取了所有 474,591 ...但是当我检查文件时,它的大小是:466,944
最终解决方案
while( ( bytesRead = OIS.read(aByte))>0)
{
fos.write(aByte,0,bytesRead);
i+=bytesRead; // i is a counter
if(i==sizeToread) break; // force to stop when read all the bytes in the file!
}