簡體   English   中英

具有矢量結構的boost :: asio :: buffer

[英]boost::asio::buffer with vectors structs

我有2個問題:

  1. 在我的信息結構中,如果我使用floatdouble類型而不是std::string則可以正常工作,但是如果我按如下方式使用std::string ,則在我的客戶端部分中會收到該結構,但之后它就會崩潰。

  2. t even send it using std :: vector` t even send it using ,就像這樣:


struct info
{
    int id;
    std::string name;
};


int main(int argc, char** argv)
{

    boost::asio::io_service ios;
    boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address::from_string("127.0.0.1"), 12345);
    boost::asio::ip::tcp::socket cl1(ios);

    cl1.open(ep.protocol());
    boost::system::error_code ec;
    cl1.connect(ep, ec);
    if (ec == 0)
        cout << "Connected" << endl;
    else {

        cout << "Not connected" << endl;
        system("pause");
        return -2;
    }

    info student;
    student.id = 7;
    student.name = "Rasul";

    cl1.send(boost::asio::buffer(&student, sizeof(student)));

    if (ec == 0)
        cout << "Written" << endl;
    else {

        cout << "Not written" << endl;
        system("pause");
        return -2;
    }
    cout << "Done" << endl;
    system("pause");
    return 0;
}
  1. 在我的信息結構中,如果我使用floatdouble類型而不是std::string則可以正常工作,但是如果我按如下方式使用std::string ,則在我的客戶端部分中會收到該結構,但之后它就會崩潰。

這是因為floatdouble是POD數據類型,而std::string不是,違反了合同:

boost::asio::buffer函數用於創建表示原始內存,POD元素數組,POD元素向量或std::string的緩沖區對象。

確切地說,它們的意思是“ [[POD元素的(數組|向量)]]或[a std::string ]” ,當您查看重載列表時,這很清楚

添加一個靜態斷言,您將看到:

static_assert(std::is_pod<info>::value, "whoops, that can't work");
cl1.send(boost::asio::buffer(&student, sizeof(student)));

如果要序列化,則必須編寫一些代碼。 假設總體上體系結構獨立性和可移植性不是問題¹,則可以:

int32_t id_and_size[] = {student.id, static_cast<int32_t>(student.name.length())};
assert(id_and_size[1] >= 0); // because `size_t` is unsigned and larger than int32_t

cl1.send(boost::asio::buffer(id_and_size));
cl1.send(boost::asio::buffer(student.name.data(), student.name.length()));

這會將長度與數據分開發送: Live On Coliru]( http://coliru.stacked-crooked.com/a/897573028a86e16e

00000000:0700 0000 0500 0000 5261 7375 6c ........ Rasul

雖然這是容易出錯和乏味的。 如果您控制兩端,請考慮使用序列化框架(Boost序列化,Google Protobuf ...)

¹因為您已經提到序列化double等的原始二進制格式。

暫無
暫無

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

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