gpt4 book ai didi

java - 客户端-服务器不发送整个文件

转载 作者:行者123 更新时间:2023-12-01 18:25:28 25 4
gpt4 key购买 nike

当我运行正在连接的客户端服务器时,我尝试发送一个文件,但它不会发送整个文件,该文件在其他地方出现错误,它大约进行到一半并不断停止在同一部分。当在同一台计算机上运行服务器客户端时,此设置有效,所以我完全困惑

服务器 --->

    // output (a DataOutputstream) is set up elsewhere and messages are sent and received properly
output.writeInt((int)file.length());
// send file

byte [] mybytearray = new byte [(int)file.length()];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
System.out.println("Sending " + file + "(" + mybytearray.length + " bytes)");
output.write(mybytearray,0,mybytearray.length);
output.flush();
System.out.println("Done.");

客户端 --->

            // input (a DataInputstream) is set up elsewhere and messages are sent and received properly
String FILE_TO_RECEIVED = "Load_From.xml";
File file = new File(FILE_TO_RECEIVED);

int FILE_SIZE = input.readInt();
if(FILE_SIZE!=0){
// receive file
System.out.println("received file size : " + FILE_SIZE);
byte [] mybytearray = new byte [FILE_SIZE];
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = input.read(mybytearray, 0, mybytearray.length);
bos.write(mybytearray, 0, bytesRead);

最佳答案

无论是读取文件还是读取套接字时,您都只读取了部分数据。 read 方法返回读取的字节数,您需要一个循环来读取所有内容。例如,

int read = 0, offset = 0;
while ((read = bis.read(mybytearray, offset, mybytearray.length - offset) != -1) {
offset += read;
}

或者您可以使用标准库中的类,例如 DataInputStream 有一个 readFully 方法。

DataInputStream dis = new DataInputStream(fis);
dis.readFully(mybytearray);

关于java - 客户端-服务器不发送整个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26362602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com