C++ – Boost, sending files over the network using tcp, prefered method


In the boost examples in the documentation, tcp:iostream is used to very simply send streams over the network. In other examples write() is used to write data to the socket instead with a bit more code involved.

What is the difference between those 2 methods? Pros and cons? Is there something else that should be used instead ?

Best Solution

I've never used the boost API, so reader beware... ;)

The tcp::iostream appears to allow you to interact with the socket with a stream-like interface. This approach abstracts the complexities associated with socket programming, so it would be preferable especially if you are new to socket programming. It makes a lot of sense for TCP-based data sharing. It is especially convenient if you are doing very simple data exchanges, such as request/response.

However, there are cases where you need lower-level control over the data exchange. If your receiver receives a bunch of messages at the same time, you may prefer to read each message from the socket instead of processing them after the fact from the iostream. On the sender side, if your messages are structured as objects, it is often easier just to send the object instead of first converting the object to a stream. The read/write functionality would be preferable in this case.

From my own (non-boost) socket programming experience, I usually prefer dealing with the lower-level functions since it gives me more flexibility even though it is slightly more complex. I hope that helps.

Related Question