1
votes

I'd like to use the method "read_some()" of boost::asio::ip::tcp::socket to fill a buffer represented as a char*.

Here is my method implementation so far:

template<class charType>
int receive_some(charType* buffer, int size)
{
     int total_received = 0;

     boost::array<charType, size> buf;
     while (1)
     {
         int received = 0;
         boost::system::error_code error;
         received = _socket.read_some(boost::asio::buffer(buf), error);
         if (error == boost::asio::error::eof)
         { 
             break;
         }
         std::cout.write(buf.data(), received);
         total_received += received;
      }

    return total_received;

}

My problem is I don't see how to convert my charType* buffer into boost::array buf. It seems expensive to iterate over the elements of my boost::array at the end of the process just to fill-in the buffer object...

Any idea ?

1
Why is it templated? Do you expect to receive anything else than bytes from the network? - Eric
Maybe he receives vegetables from the sockets... in that case it would have to be a template. But yeah... template not needed here. - Blacktempel
I could receive char*, unsigned char * etc, no? - Julien Greard

1 Answers

4
votes
template<class charType>
int receive_some(charType* buffer, int size)
{
     int total_received = 0;

     while (1)
     {
         int received = 0;
         boost::system::error_code error;
         received = _socket.read_some(boost::asio::buffer(buffer, size), error);
         if (error == boost::asio::error::eof)
         { 
             break;
         }
         std::cout.write(buffer, received);
         total_received += received;
      }

    return total_received;

}

The boost::asio::buffer function has a lot of overloads to allow to create an asio buffer from diffrent types of sources.

It's worth noting that size has to be the number of bytes to read into buffer and not the number of charType.

Bonus tip: As comments pointed out, that template is suspicious, the best you could do with it is directly write into wide strings but that might better be somewhere else than in a read_some function (actually it might even be better nowhere), in a network function you deal with bytes not characters so you'd better take a simple char* or even void* as a type for the buffer parameter.