![](https://csdnimg.cn/release/download_crawler_static/87232471/bg13.jpg)
Getting Started with Boost.Asio
[ 8 ]
Important macros
Use BOOST_ASIO_DISABLE_THREADS if set; it disables threading support in Boost.
Asio, regardless of whether Boost was compiled with threading support.
Synchronous versus asynchronous
First off, asynchronous programming is extremely different than synchronous
programming. In synchronous programming, you do the operations in sequential
order, such as read (request) from socket S, then write (answer) to socket. Each
operation is blocking. Since operations are blocking, in order not to interrupt the
main program while you're reading from or writing to a socket, you'll usually
create one or more threads that deal with socket's input/output. Thus, synchronous
servers/clients are usually multi-threaded.
In contrast, asynchronous programming is event-driven. You start an operation,
but you don't know when it will end; you supply a callback, which the API will
call when the operation ends, together with the operation result. To programmers
that have extensive experience with QT, Nokia's cross-platform library for creating
graphical user interface applications, this is second nature. Thus, in asynchronous
programming, you don't necessary need more than one thread.
You should decide early on in your project (preferably at the start) whether you go
synchronous or asynchronous with networking, as switching midway will be very
difcult and error-prone; not only will the API differ substantially, the semantic of
your program will change completely (asynchronous networking is usually harder
to test and debug than synchronous networking). You'll want to think of either going
for blocking calls and multi-threading (synchronous, usually simpler) or less-threads
and events (asynchronous, usually more complex).
Here's a basic example of a synchronous client:
using boost::asio;
io_service service;
ip::tcp::endpoint ep( ip::address::from_string("127.0.0.1"), 2001);
ip::tcp::socket sock(service);
sock.connect(ep);
First, your program needs at least an io_service instance. Boost.Asio uses
io_service to talk to the operating system's input/output services. Usually one
instance of an io_service will be enough. Next, create the address and port you
want to connect to. Create the socket. Connect the socket to your address and port: