I'm using the asio 1.18.1 standalone version (no boost) and I wonder about the difference between asio::connect and asio::async_connect.
asio::connect
attempts to connect a socket at the point of call and will block until connection is established. In other words, if it takes eg 20 seconds to resolve a DNS address, it will block for the entire duration.
asio::async_connect
will simply queue up connection request and will not actually do anything until you call io_context.run()
(or other functions, such as run_once()
, etc).
I can tell myself why I need async for my server, because the point of async is being able to deal with a lot of data on a lot of different connections at the same time.
I can neither confirm nor deny that.
But when it comes to the client, I really need just one non-blocking thread and isn't async for just one thread useless?
Not necessarily. If you want to do other things on the same thread, eg show connection progress, execute periodic timer or run interactive GUI, etc. If you call asio::connect
, your GUI will freeze until the function returns. You can choose to call asio::connect
on a separate thread than your GUI, but then you need to worry about thread synchronization, locks, mutexes, etc.
Is asio::connect a non-blocking sync, because that's what I really need?
I don't really understand this question, but asio::connect
is blocking.
If it's a blocking sync, then I would rather choose the asio::async_connect. Same question about asio::async_read and asio::async_write.
asio::connect
, asio::read
and asio::write
are all blocking. In other words, they will execute at the point of call and will block until done.
asio::async_connect
, asio::async_read
and asio::async_write
are their async (non-blocking) counterparts. When you call either one, they will be queued for execution and will be executed once you call io_context.run()
. (I am simplifying a bit, but that's the basic concept.)