1

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?

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
Rella
  • 65,003
  • 109
  • 363
  • 636
  • 3
    This is something you can do in your own code. You don't need any help from boost. – J T Aug 17 '11 at 04:24
  • @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 Aug 17 '11 at 19:30

1 Answers1

1

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 );
}
Sam Miller
  • 23,808
  • 4
  • 67
  • 87
  • Or in case like I have where I pass shared_ptr to boost socket to some service class that is inside some shared library (which is not built by me - server author) it is easier to create tcp proxy service in between user and end service. – Rella Aug 17 '11 at 19:21