2

我想创建一个客户端-服务器程序,允许客户端向服务器发送文件以及有关文件的一些信息(发件人姓名、描述等)。

该文件可能非常大,因为它可能是文本、图片、音频或视频文件,因此我不想在发送之前将整个文件读入字节数组,我宁愿读取文件在块中,通过网络发送它们,然后允许服务器将块附加到文件的末尾。

但是,我面临如何最好地发送文件以及有关文件本身的一些信息的问题。我希望至少发送发件人的姓名和描述,这两者都将由用户输入到客户端程序,但这可能会在未来发生变化,所以应该灵活。

这样做的好方法是什么,它还可以让我“流式传输”正在发送的文件,而不是把它作为一个整体读取然后发送?

4

3 回答 3

2

套接字本身就是字节流,所以你不应该有问题。我建议你有一个看起来像这样的协议。

只要总长度小于 64 KB,这将允许您发送任意属性。随后是可以是任何 63 位长度的文件,并且一次发送一个块。(使用 8 KB 的缓冲区)

如果您愿意,可以使用 Socket 发送更多文件。

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();
于 2011-02-17T19:40:41.990 回答
0

您可以围绕众所周知的协议(如 FTP)构建程序。要发送元信息,您只需创建一个包含信息的唯一名称的特殊文件。然后使用 FTP 传输用户文件和元文件。

否则,再次使用 FTP 文件,您可以在您的手写程序的客户端-服务器流中传输元数据。

于 2011-02-17T19:41:43.083 回答
0

我建议为此使用 http 协议。服务器可以使用 servlet 实现,而Apache HttpClient可以用于客户端。这篇文章有一些很好的例子。您可以在同一个请求中同时发送文件和参数。而且代码很少!

于 2011-02-17T19:50:18.693 回答