1
votes

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?

1
This is something you can do in your own code. You don't need any help from boost.J T
@J T: I try to create an extendable server. I have a concept of services. I pass socket to each service on each user request. And I want to get how much traffic this connection has used.Rella

1 Answers

1
votes

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 );
}