我需要能够读取文件,将其分解为任意大小的数据包,比如说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)