簡體   English   中英

streambuf with boost :: asio :: async_write

[英]streambuf with boost::asio::async_write

告訴我如何使用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 (異步)寫入和解鎖之前獲取鎖定。

如果緩沖區是連接的本地緩沖區,並且您不在其他線程中訪問它,則無需鎖定或復制。 這與沒有使用Asio的任何地方沒有什么不同。

需要在同一插座上進行同步操作: 為什么我需要每個連接擱淺使用boost :: ASIO什么時候?

要發送整個緩沖區,只需使用boost::asio::async_write

注意:您應該在完成處理程序的bind中使用shared_from_this()而不是this

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM