问题描述
我目前正在制作一个文件传输服务器,它通过 DatagramPacket 从文件中获取 1024 字节的块(这是分配的要求),然后在通过 HTTP 发送之前将文件组装在字节数组中。该系统适用于任何文本文件格式,甚至是非常大的 .c/.txt/.sql 文件,所以我知道我正在获取正确的字节。但是,当我尝试使用其他任何内容(例如 .zip 或 .png)时,当我在另一侧打开它时,它会损坏。这也发生在非常小的图像/zip 中。知道为什么会发生这种情况吗?
来自创建块的类的代码:
File f = new File(campos[2]);
FileInputStream inputStream = new FileInputStream(f);
inputStream.skipNBytes(chunk);
if (f.length() > chunk + 1024)
quantos = 1024;
else quantos = (int) f.length() - chunk;
byte[] dados = new byte[quantos];
inputStream.read(dados,quantos);
inputStream.close();
pacote = new DatagramPacket(dados,quantos,address,porta);
socket.send(pacote);
while (tamanho > 0) {
serv = procuraServidor();
buf = ("Chunk " + chunk + " " + parametros[1].substring(1) + " ").getBytes();
pacote = new DatagramPacket(buf,buf.length,serv.getKey(),serv.getValue());
dataSocket = new DatagramSocket();
//pede os dados desse chunk
dataSocket.send(pacote);
buf = new byte[1500];
pacote = new DatagramPacket(buf,buf.length);
dataSocket.receive(pacote);
try {
lock.lock();
servidores.add(serv);
} finally {
lock.unlock();
}
if (tamanho > chunkSize)
System.arraycopy(buf,ficheiro,chunk*chunkSize,chunkSize);
else System.arraycopy(buf,tamanho);
// iniciar thread para tomar conta do pedido
tamanho-= chunkSize;
chunkSet.add(chunk);
chunk++;
}
out.write("HTTP/1.1 200 OK\r\n".getBytes());
out.write(("content type: " + Files.probeContentType(new File (parametros[1].substring(1)).toPath())).getBytes());
out.write(ficheiro);
out.flush();
}
我真的不知道为什么会发生这种情况,特别是在非文本文件中。
解决方法
据我所知,您不会在 content-type 之后发送 CRLF,也不会发送 content-length,而且也没有 CRLF 将内容与标头字段分开。