views:

636

answers:

2

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 ?

+1  A: 

I haven't used boost for network communications but I guess that the "ip::tcp" set of classes wrap the underlying socket based communication in c++. Using the boost method might be simpler since it has already implemented asynchronous communication. Normal socket communication is flexible but cumbersome. Use it only if the application is performance critical. But there are some pitfalls with "ip::tcp" such as having to flush the stream every time you write something to it (<< std::flush) but I think the advantages out weigh the disadvantages.

Gayan
+1  A: 

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.

Matt Davis