【发布时间】:2011-05-27 13:54:02
【问题描述】:
我正在处理一个项目,并且对 Java 套接字有疑问。可以在here找到源文件。
在以纯文本成功传输文件大小后,我需要传输二进制数据。 (DVD .Vob 文件)
我有一个循环,例如
// Read this files size
long fileSize = Integer.parseInt(in.readLine());
// Read the block size they are going to use
int blockSize = Integer.parseInt(in.readLine());
byte[] buffer = new byte[blockSize];
// Bytes "red"
long bytesRead = 0;
int read = 0;
while(bytesRead < fileSize){
System.out.println("received " + bytesRead + " bytes" + " of " + fileSize + " bytes in file " + fileName);
read = socket.getInputStream().read(buffer);
if(read < 0){
// Should never get here since we know how many bytes there are
System.out.println("DANGER WILL ROBINSON");
break;
}
binWriter.write(buffer,0,read);
bytesRead += read;
}
我读取了接近 99% 的随机字节数。我正在使用基于 TCP 的 Socket, 所以我不必担心低层传输错误。
收到的号码会发生变化,但总是非常接近尾声 在文件 GLADIATOR/VIDEO_TS/VTS_07_1.VOB 中收到 7266304 字节的 7258144 字节
然后应用程序会在阻塞读取中挂起。我很困惑。服务器正在发送正确的 文件大小并在 Ruby 中成功实现,但我无法让 Java 版本工作。
为什么我读取的字节数少于通过 TCP 套接字发送的字节数?
以上是由于你们中的许多人在下面指出的一个错误。
BufferedReader 吃了我的套接字输入的 8Kb。可以找到正确的实现 Here
【问题讨论】:
-
在这个问题上我已经把头撞在桌子上很长一段时间了......
标签: java sockets file-io file-upload tcpclient