gpt4 book ai didi

java - 套接字编程Java : How to receive multiple files from outputstream?

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

我的服务器正在向我的客户端发送多个文件。然而在客户端,它只接收第一个文件,因为我不知道如何迭代并获取第二个文件。

服务器发送如下:

ListIterator iter = missingfiles.listIterator(); 
//missingfiles contain all the filenames to be sent
String filename;
while (iter.hasNext()) {
// System.out.println(iter.next());
filename=(String) iter.next();
File myFile = new File("src/ee4210/files/"+filename);
byte[] mybytearray = new byte[(int) myFile.length()];

FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
//bis.read(mybytearray, 0, mybytearray.length);

DataInputStream dis = new DataInputStream(bis);
dis.readFully(mybytearray, 0, mybytearray.length);

OutputStream os = _socket.getOutputStream();

//Sending file name and file size to the server
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(myFile.getName());
dos.writeLong(mybytearray.length);
dos.write(mybytearray, 0, mybytearray.length);
dos.flush();
}

客户端接收是这样的:(它只会接收第一个文件,我不知道如何让它循环接收下一个文件)

int bytesRead;
int current = 0;
int filecount = 0;
InputStream in;
try {
in = _socket.getInputStream();
DataInputStream clientData = new DataInputStream(in);
String fileName = clientData.readUTF();
OutputStream output = new FileOutputStream(
"src/ee4210/files/"+ fileName);
long size = clientData.readLong();
byte[] buffer = new byte[1024];
while (size > 0
&& (bytesRead = clientData.read(buffer, 0,
(int) Math.min(buffer.length, size))) != -1) {
output.write(buffer, 0, bytesRead);
size -= bytesRead;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

最佳答案

How to receive multiple files from outputstream?

显而易见的答案是“一次一个,并提供额外信息来告诉您一个在哪里停止,另一个从哪里开始”。最常用的技术是在文件之前发送文件大小,例如通过 DataOutputStream.writeLong() 作为 long,并在接收器处更改读取循环以在恰好那么多字节后停止,关闭输出文件,并继续读取下一个 long 或 end 的外部循环-of-stream。

关于java - 套接字编程Java : How to receive multiple files from outputstream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15137653/

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