I am first time writing a simple single threaded tcp client in C++ that requests some data from server and main thread should block until we receive response or failure from server. So what I am planning to do is below ..
write(......) // writes struct as char buffer
read(.....) // blocks until data is received or error
So my question is, is this approach correct? I feel there should be alternative solution available using select
where client wil block on select
until socket becomes readable. Can anyone suggest what would be best in this scenario and why?
Thanks in advance.
For a simple client-side TCP conversation it's fine to use regular, blocking write
and read
calls - the write
will return immediately (as long as there's space in the send buffer) and the read
will block until some data is received (or an error occurs). The obvious downside here is that nothing can be sent while you wait to receive. This is fine with most synchronous ("request-reply") type of communication protocols.
select
is useful for managing multiple parallel I/O operations in more complex scenarios. For example, if you have to send and receive two streams which are unsynchronized with respect to each other - meaning the sending can continue indefinitely even if receiving is blocked, or vice versa, then you can select
on the socket fd for reading and writing simultaneously, and then perform write
, read
or both, depending on which side is available, without blocking.