我需要能够读取一个文件,将它分成一些任意大小的数据包,比如说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)
parts
读取,以确保你能接收到所有内容。只需循环等待直到有东西可以读取... - DejanLekic