gpt4 book ai didi

c++ - streambuf 与 boost::asio::async_write

转载 作者:太空狗 更新时间:2023-10-29 21:41:35 25 4
gpt4 key购买 nike

告诉我如何将 boost::asio::streambufboost::asio::async_write 一起使用。我有一个连接到它的一个客户端的服务器应用程序。

我为每个连接创建对象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;
};

最佳答案

在使用 async_write 时要格外小心,你不应该将 async_write 重叠到同一个流中(参见规范 http://www.boost.org/doc/libs/1_51_0/doc/html/boost_asio/reference/async_write/overload1.html )。我不确定你是否真的需要异步写入,只要你不需要传输那么多数据并并行做其他事情......如果你真的需要它,那么你应该确保同步。您可以使用一些锁定机制,在(异步)写入之前获取锁定并在 WriteHandler 中解锁。

关于c++ - streambuf 与 boost::asio::async_write,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28579638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com