告诉我如何使用boost::asio::streambuf
with boost::asio::async_write
。我有一个连接到一个客户端的服务器应用程序。
我为每个连接创建 object tcp_connection
。
如果我需要向客户端发送多个连续消息,如何正确创建用于发送数据的缓冲区?
我是否需要同步调用 Send() 因为它们使用全局缓冲区来发送?还是我需要在调用之前创建一个单独的缓冲区async_write
?
例如,在使用 IOCP 的 Windows 中,我创建了自己的包含缓冲区的 OVERLAPPED 结构。我在调用 WSASend 之前创建一个缓冲区,并在操作完成后删除,从 OVERLAPPED 结构中提取它。即每个WSASend 都有自己的缓冲区。
怎么办boost::asio::async_write
?
我在这里上课tcp_connection
#include <boost/asio.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/bind.hpp>
#include <iostream>
class tcp_connection
// Using shared_ptr and enable_shared_from_this Because we want to keep the
// tcp_connection object alive As long as there is an operation that refers to
// it.
: public boost::enable_shared_from_this<tcp_connection> {
tcp_connection(boost::asio::io_service& io) : m_socket(io) {}
void send(std::string data) {
{
std::ostream stream(&send_buffer);
stream << data;
}
std::cout << "Send Data =" << data << std::endl;
std::cout << "Send Buffer =" << make_string(send_buffer) << std::endl;
boost::asio::async_write(m_socket, send_buffer,
boost::bind(&tcp_connection::handle_send, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void handle_send(const boost::system::error_code &error, size_t);
private:
static std::string make_string(boost::asio::streambuf const&) { return "implemented elsewhere"; }
boost::asio::ip::tcp::socket m_socket;
boost::asio::streambuf send_buffer;
};