簡體   English   中英

Boost ASIO SSL收到的字節數

[英]Boost ASIO SSL number of bytes received

我想使用Boost ASIO + SSL創建客戶端/服務器通信程序對。 因此,我從boost提供的示例開始,我了解了它是如何工作的,除了有一個問題外,我幾乎准備開發我的通信協議。

因此,從本示例開始,我將在握手后修改handle_read()回調函數。 以下是我的代碼。 我唯一的修改是:添加另一個名為startComm()回調函數,它將開始通信。

void handle_read(const boost::system::error_code& error,
                 size_t bytes_transferred)
{
    if (!error)
    {
        std::cout << "Reply: ";
        std::cout.write(reply_, bytes_transferred);
        std::cout << "\n";

        boost::asio::async_write(socket_,
                                 boost::asio::buffer(std::string("Now?")),
                                 boost::bind(&SSLClient::startComm, this,
                                             boost::asio::placeholders::error,
                                             boost::asio::placeholders::bytes_transferred));
    }
    else
    {
        std::cout << "Read failed: " << error.message() << "\n";
    }
}

void startComm(const boost::system::error_code& error,
                 size_t bytes_transferred)
{
    if (!error)
    {
        std::cout << "Reply: ";
        std::cout.write(reply_, bytes_transferred); //problem here, bytes transferred should contain the number of received chars not number of written chars
        std::cout << "\n";
    }
    else
    {
        std::cout << "Read failed: " << error.message() << "\n";
    }


}

在上面的async_write() ,有一個參數boost::asio::placeholders::bytes_transferred可以參數化我的回調函數以提供發送到服務器的字節數 現在我想知道服務器響應的字節數 在我的簡單示例中,我該怎么做?

謝謝。 如果您需要任何其他詳細信息,請詢問。

write調用發送數據。

因為它不,在所有, 接收數據接收到的字節的數量是通過定義0。

如果要接收數據,請使用(async_)read ,它會告訴您接收到的字節數。

這些bytes_transferred使用相同的占位符bytes_transferred ),但根據已完成的傳輸方向,它具有不同的含義。

這是一個從技術上講 startComm您需要的解決方案:定義一個額外的startComm參數並將其綁定(不帶占位符)。

void handle_read(const boost::system::error_code &error, size_t bytes_received) {
    if (!error) {
        std::cout << "Reply: ";
        std::cout.write(reply_, bytes_received);
        std::cout << "\n";

        boost::asio::async_write(socket_, boost::asio::buffer(std::string("Now?")),
                                 boost::bind(&SSLClient::startComm, 
                                     this, 
                                     boost::asio::placeholders::error,
                                     bytes_received,
                                     boost::asio::placeholders::bytes_transferred));
    } else {
        std::cout << "Read failed: " << error.message() << "\n";
    }
}

void startComm(const boost::system::error_code &error, size_t had_received, size_t bytes_sent) {
    if (!error) {
        std::cout << "Reply: ";
        std::cout.write(reply_, had_received);
        std::cout << "\n";
    } else {
        std::cout << "Write failed: " << error.message() << "\n";
    }
}

請注意,我仍然認為您可能會誤以為 async_write會收到回復,(顯然是這樣)

暫無
暫無

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

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