我想创建一个客户端-服务器程序,允许客户端将文件连同有关文件的一些信息(发件人姓名、描述等)发送到服务器。
文件可能非常大,因为它可能是文本、图片、音频或视频文件,因此我不想在发送前将整个文件读入字节数组,我宁愿以 block 的形式读取文件,通过网络发送它们,然后允许服务器将 block 附加到文件的末尾。
但是,我面临着如何最好地发送文件以及有关文件本身的一些信息的问题。我希望至少发送发件人的姓名和描述,这两者都将由用户输入到客户端程序,但这在未来可能会发生变化,因此应该灵活。
执行此操作的好方法是什么,它还允许我“流式传输”正在发送的文件,而不是将其作为一个整体读取然后发送?
最佳答案
套接字本身就是字节流,所以你应该不会有问题。我建议你有一个看起来像这样的协议(protocol)。
这将允许您发送任意属性,只要总长度小于 64 KB。紧随其后的文件可以是任意 63 位长度,并且一次发送一个 block 。 (带 8 KB 缓冲区)
如果您愿意,可以使用套接字发送更多文件。
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
Properties fileProperties = new Properties();
File file = new File(filename);
// send the properties
StringWriter writer = new StringWriter();
fileProperties.store(writer, "");
writer.close();
dos.writeUTF(writer.toString());
// send the length of the file
dos.writeLong(file.length());
// send the file.
byte[] bytes = new byte[8*1024];
FileInputStream fis = new FileInputStream(file);
int len;
while((len = fis.read(bytes))>0) {
dos.write(bytes, 0, len);
}
fis.close();
dos.flush();
阅读
DataInputStream dis = new DataInputStream(socket.getInputStream());
String propertiesText = dis.readUTF();
Properties properties = new Properties();
properties.load(new StringReader(propertiesText));
long lengthRemaining = dis.readLong();
FileOutputStream fos = new FileOutputStream(outFilename);
int len;
while(lengthRemaining > 0
&& (len = dis.read(bytes,0, (int) Math.min(bytes.length, lengthRemaining))) > 0) {
fos.write(bytes, 0, len);
lengthRemaining -= len;
}
fos.close();
关于java - 通过网络发送具有自定义属性的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5033582/