我的服务器正在向我的客户端发送几个文件。但是在客户端,它只接收第一个文件,因为我不知道如何迭代并获取第二个文件。Socket编程Java:如何从outputstream接收多个文件?
服务器发送这样的:
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();
}
“我不知道如何让它循环接收下一个文件” - 呃......只是在读取文件的行周围放一个'while' (从'String fileName = ...'开始,并在'catch(...)'块之前结束,也许可以从客户端添加一个sentinel值,告诉您它已经完成发送文件,或者让它发送文件数它会在传输开始时发送,或者只是关闭连接并让'while'循环继续,直到发生这种情况。 – millimoose 2013-02-28 14:20:17
当你在服务器上使用'DataOutputStream'时,你为什么不读取数据'DataInputStream'在客户端?我猜你实际读的内容可能最终会出现乱码,如果'DOS'没有像你想象的那样真正直接输出数组。 – millimoose 2013-02-28 14:22:50
我不知道该怎么做。 new to Java。我现在该做什么? – Ferrino 2013-02-28 15:28:13