【发布时间】:2012-01-12 07:19:35
【问题描述】:
我需要能够读取文件,将其分成任意大小的数据包,比如说 512 字节,然后通过 TCP 发送这些数据包。问题是,接收方没有收到我发送的所有字节。如果我发送 1000 个数据包,接收方在从 InputStream 读取时会阻塞,因为他没有更多数据要读取大约 990 个数据包左右。
这是代码(只是发送和接收部分):
发件人:
int parts = (int)Math.ceil((double)(file.length()/512.0));
out.println(parts+"");
int readFile;
int i = 0;
while ((readFile = fileIn.read(buffer)) != -1) {
i++;
fileOut.write(buffer, 0, readFile);
fileOut.flush();
System.out.println("-- Sent packet " + i + "/" + parts + ". " + "Bytes sent = " + readFile);
}
接收者:
int parts = Integer.parseInt(in.readLine());
byte[] buffer = new byte[512];
FileOutputStream pw = new FileOutputStream("file.ext");
DataInputStream fileIn = new DataInputStream(socket.getInputStream());
for(int j = 0; j < parts; j++){
int read = 0;
if(j == parts - 1){
read = fileIn.read(buffer);
pw.write(buffer, 0, read);
}else{
fileIn.readFully(buffer);
pw.write(buffer);
}
System.out.println("-- Received packet " + (j+1) + "/" + parts + ". Read " +read+ " bytes.");
}
我尝试增加套接字的发送和接收缓冲区大小,但没有成功。我错过了什么?
这是一个输出示例:
发件人:
-- Sent packet 1/10. Bytes sent = 512
-- Sent packet 2/10. Bytes sent = 512
-- Sent packet 3/10. Bytes sent = 512
-- Sent packet 4/10. Bytes sent = 512
-- Sent packet 5/10. Bytes sent = 512
-- Sent packet 6/10. Bytes sent = 512
-- Sent packet 7/10. Bytes sent = 512
-- Sent packet 8/10. Bytes sent = 512
-- Sent packet 9/10. Bytes sent = 512
-- Sent packet 10/10. Bytes sent = 234
接收者:
-- Received packet 1/10. Read 512 bytes.
-- Received packet 2/10. Read 512 bytes.
-- Received packet 3/10. Read 512 bytes.
-- Received packet 4/10. Read 512 bytes.
-- Received packet 5/10. Read 512 bytes.
-- Received packet 6/10. Read 512 bytes.
-- Received packet 7/10. Read 512 bytes. (And it blocks here, because there is no more data to read)
【问题讨论】:
-
您可能永远无法 100% 确定您会以
parts的形式发送内容。你一直写,直到写完。buffer的大小是多少?您基本上需要深入了解并继续写入 fileOut,直到您写入缓冲区的全部内容。 -
buffer具有所需的数据包大小,在本例中为 512 字节。根据我的输出,文件总是设法在parts数据包中发送。 -
我认为你的接收器坏了。你不应该相信你会收到
parts读取的所有内容。只需循环,直到您有要阅读的内容... -
我添加了一个示例输出。
-
我试过了,但问题仍然存在......例如,如果我发送一个 1213234 字节的文件,大多数情况下接收者会阻塞这条消息
-- Read 314 bytes. (1206066/1213234),这意味着 - (bytesRead/TotalBytes) .