5. boost asio tutorial---asynchronous TCP server

Now it's time to look at our first Boost.Asio asynchronous TCP server. This is the last time I won't use namespaces and type aliases. I'll use that next time because the name gets too long and you already know where things are coming from.

This time, our server does the following:

- Listen on port 15001 for incoming TCP connections.
- Accept incoming connections.
- Read data from the connection until a newline character "\n" is "seen".
- Write the received data (or string) to standard output.
- Close the connection.

Take a look at the complete example. Let's break it down into parts and see what's going on in each part. Error handling is omitted for clarity. We'll discuss error handling later.

#include <iostream>
#include <optional>
#include <boost/asio.hpp>

class session : public std::enable_shared_from_this<session>
{
public:

    session(boost::asio::ip::tcp::socket&& socket)
    : socket(std::move(socket))
    {
    }

    void start()
    {
        boost::asio::async_read_until(socket, streambuf, '\n', [self = shared_from_this()] (boost::system::error_code error, std::size_t bytes_transferred)
        {
            std::cout << std::istream(&self->streambuf).rdbuf();
        });
    }

private

Guess you like

Origin blog.csdn.net/Knowledgebase/article/details/132859995