David Moreno García
David Moreno García

Reputation: 4523

Send multiple files with file id in a same socket connection

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?

Upvotes: 0

Views: 180

Answers (1)

nos
nos

Reputation: 229234

You need to delimit the TCP stream, so you can know when one file starts and ends. You need to create your own protocol.

One simple thing to do is to first send a small fixed length header with the file id and file size.

e.g.

  • Send 'file-id' a 4 byte file id
  • Send 'file-size a 8 byte file size
  • Send the file content, of 'file-size' bytes.

This can be repeated as many times you need it to over the same TCP socket.

The receiving end would need to:

  • Read 4 bytes, interpret it as the file-id
  • Read 8 bytes, interpret it as the file-size
  • Read 'file-size'(from the previous step) bytes , which is the file content.

Once all the bytes are received, it can start over again, reading a new header of file-id and file-size.

Upvotes: 2

Related Questions