Sending/receiving files using a TCP connection
Sending and receiving files over a TCP connection demonstrates several important points about network programming, namely the protocol design (which deals with who sends what when) and encoding (which deals with how data elements are represented on the wire). This example will show how to transfer metadata and an octet stream over a TCP connection.
How to do it...
- Use the same structure to set up the server as in the previous section.
- On the sender end (client), do the following:
- Encode file metadata containing the filename, size, and mode and send it.
- Send the contents of the file.
- Close the connection.
- On the receiver end (server), do the following:
- Decode file metadata. Create a file to store the received file contents with the given mode.
- Receive file contents and write the file.
- After all file content is received, close the file.
The first part is the transfer of metadata about the file. There are several ways...