使用套接字class的成员函数还是Boost::asio中的普通函数?

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

我正在学习Boost::asio套接字;我看到一些 examples,他们使用 socket class 的成员函数来读取和接收消息,或者使用 boost::asio 将 socket 作为第一个参数传递的公共函数。

所以我想知道这两种方法之间有什么区别?谢谢!

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

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

async_write 作为静态函数保证缓冲区中的所有数据 写在这个函数之前 returns.

async_write_some 作为函数成员保证至少一个字节 在此函数结束之前从缓冲区写入。

所以如果你想使用async_write_some你需要提供更多的代码 处理缓冲区中并非所有数据都已写入的情况。

假设你有 10 个字节的字符串,它是你的缓冲区,你想确保 所有缓冲区都已发送:

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

在回调[1]中你需要检查写入了多少字节, 如果结果与 SIZE 不同,您需要再次调用 async_write_some 发送剩余数据等,您的回调可能会被调用多次。

async_write的使用更简单:

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

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

如果 [1] 中没有出现错误,您就知道所有数据都已发送。