Gordon
Gordon

Reputation: 446

use member function of socket class or common function in Boost::asio?

I am learning Boost::asio socket; I saw some examples, where they use the member function of socket class to read and receive messages, or use the boost::asio common function which passes the socket as the first param.

So I am wondering what the difference is between the two approaches? thanks!

//one kind
tcp::socket sock;
sock.async_write_some(***);

//another kind
boost::asio::async_write(socket,***);

Upvotes: 0

Views: 158

Answers (1)

rafix07
rafix07

Reputation: 20936

async_write as static function guarantees that all data in buffer is written before this function returns.

async_write_some as function member guarantees that at least one byte is written from buffer before this function ends.

So if you want to use async_write_some you need to provide more code to handle the situation when not all data from buffer was written.

Suppose you have string with 10 bytes, it is your buffer and you want to ensure all buffer is send:

// Pseudocode:

string str;
// add 10 bytes to str
SIZE = 10;
int writtenBytes = 0;
socket.async_write_some (buffer(str.c_str(),SIZE), makeCallback());

void callback (
    error_code ec,
    size_t transferredBytes)
{
    // check errors

    // [1]
    writtenBytes += transferredBytes;
    if (writtenBytes == SIZE)
         return;

    // call async_write_some 
    socket.async_write_some (buffer(str.c_str()+writtenBytes,SIZE-writtenBytes),makeCallback());
}

in callback [1] you need to check how many bytes were written, if result is different from SIZE you need to call async_write_some again to send the remainder of data and so on, your callback may be invoked many times.

The use of async_write is simpler:

string str; // add 10 bytes
async_write (buffer(str.c_str(),SIZE),makeCallback());

void callback() {
  // check errors
  [1]
}

if no errors occured in [1] you know that all data was sent.

Upvotes: 1

Related Questions