Search code examples
c++boosttcpboost-asiotraffic-measurement

How to find out how much data was sent through a Boost ASIO TCP socket connection?


I have some shared pointers to boost::asio::io_service, boost::asio::ip::tcp::endpoint, boost::asio::ip::tcp::acceptor and boost::asio::ip::tcp::socket. I accept users connection and pass shared_ptr of the socket to some class of mine. It does its work.

Now what I want is simple - count my traffic. I want to get information of how much data was sent and received during that connection. How to get such information from accepted Boost ASIO TCP socket?


Solution

  • Assuming you use asynchronous methods, the completion handler given to async_read will indicate the number of bytes received. Similarly, the completion handler given to async_write will indicate the number of bytes written. It would be trivial to maintain a running counter as a member of a class where you bind methods as the previously described completion handlers.

    #include <boost/asio.hpp>
    
    #include <iostream>
    
    class Socket
    {
    public:
        Socket(
                boost::asio::io_service& io_service
              ) :
            _socket( io_service ),
            _counter( 0 )
        {
    
        }
    
        void readHandler(
                const boost::system::error_code& error,
                std::size_t bytes_transferred
                )
        {
            _counter += bytes_transferred;
        }
    
        void writeHHandler(
                const boost::system::error_code& error,
                std::size_t bytes_transferred
                )
        {
            _counter += bytes_transferred;
        }
    
    private:
        boost::asio::ip::tcp::socket _socket;
        std::size_t _counter;
    };
    
    int
    main()
    {
        boost::asio::io_service io_service;
        Socket foo( io_service );
    }