CodeBlanks Logo Icon CodeBlanks

Boost.Asio

Learn async networking with Boost.Asio.

What is Boost.Asio?

Boost.Asio is a cross platform asynchronous I/O library for C++. It is used for both networking and timers. Unlike POSIX sockets it offers a non-blocking model; this lets a single thread handle thousands of connections.

Core components: boost::asio::io_context event loop, tcp::socket socket, tcp::acceptor server acceptor. Example: boost::asio::io_context io; boost::asio::ip::tcp::socket sock(io);. Operations are started with callback methods like async_read and async_write. io.run() runs the event loop. This lesson covers the basic setup.

io_context and tcp::socket

boost::asio::io_context is the heart of Asio: the event loop that manages all asynchronous operations. When you create a socket or timer you bind it to an io_context. Operations are started but do not finish immediately; they complete when io.run() is called.

Example: boost::asio::io_context io; boost::asio::ip::tcp::socket sock(io);. Here sock is bound to io; all its operations are managed by io. To start an async operation you use methods like sock.async_write_some(buffer, handler). The handler is a callback called when the operation completes (it can be a lambda). io.run() runs all pending operations.

Practice Create an Asio socket

Add #include <boost/asio.hpp>. Define boost::asio::io_context io;. Create a socket with boost::asio::ip::tcp::socket sock(io);. Print std::cout << "Asio ready";.

Starter code

main.cpp
#include <iostream>

// Add the Boost.Asio header and io_context

int main() {
    // Create io_context and tcp::socket
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <boost/asio.hpp>

int main() {
    boost::asio::io_context io;
    boost::asio::ip::tcp::socket sock(io);
    std::cout << "Asio ready";
    return 0;
}

Expected output

Asio ready

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the main advantage of Boost.Asio?

  • It produces smaller files
  • Fewer lines of code
  • Asynchronous and non-blocking operation Correct answer
  • It only works on Windows

Explanation: With its async model Asio handles many connections on one thread.

2 Match each piece to its role

Term Meaning
boost::asio::io_context Event loop
tcp::socket Socket
tcp::acceptor Connection accept
io.run() Runs the loop

3 Complete the io_context type

Question
boost::asio::____ io;
Answer
boost::asio::io_context io;

Explanation: boost::asio::io_context defines the event loop.

All lessons in Advanced