0

I need to send some files over a socket and I'm trying to figure out how to do it. It's pretty easy to send a single file, but I need to, once I'm connected, send an integer that represent a file unique id and after that send file content. Once completed, I have to send another id with its file content. So I need to have something like this:

  1. Connect
  2. If there aren't file to send go to 6
  3. Send id
  4. Send file
  5. Go to 2
  6. Close connection

Most of the solutions that I've found to send files use a byte[] as buffer and I don't know how to differentiate the id from the file content. What can I do?

4

1 回答 1

2

您需要分隔 TCP 流,以便知道一个文件何时开始和结束。您需要创建自己的协议。

要做的一件简单的事情是首先发送一个带有文件 id 和文件大小的固定长度的小标题。

例如

  • 发送 'file-id' 一个 4 字节的文件 id
  • send 'file-size 一个 8 字节的文件大小
  • 发送“文件大小”字节的文件内容。

这可以在同一个 TCP 套接字上重复多次。

接收端需要:

  • 读取 4 个字节,将其解释为 file-id
  • 读取 8 个字节,将其解释为文件大小
  • 读取“文件大小”(来自上一步)字节,这是文件内容。

收到所有字节后,它可以重新开始,读取文件 ID 和文件大小的新标头。

于 2013-06-25T09:12:46.073 回答