gpt4 book ai didi

c++ - 带有 vector 结构的 boost::asio::buffer

转载 作者:太空宇宙 更新时间:2023-11-03 17:25:46 26 4
gpt4 key购买 nike

我有两个问题:

  1. 在我的信息结构中,如果我有 floatdouble 类型而不是 std::string 它工作正常,但如果我使用 std::string 如下,在我的客户端部分我收到了结构,但之后它就崩溃了。

  2. 我什至不能使用std::vector` 发送它,像这样:


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. In my info structure if I have float or double types instead of std::string it works fine, but if I use std::string as below, in my client part i receive the struct but after that it just crashes.

那是因为floatdouble是POD数据类型而std::string不是,违反约定:

The boost::asio::buffer function is used to create a buffer object to represent raw memory, an array of POD elements, a vector of POD elements, or a std::string

准确地说,它们的意思是“POD元素的一个(数组| vector )]或[一个std::string]”,当你看看 list of overloads

添加一个静态断言,你会看到:

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 .......拉苏尔

虽然这很容易出错且乏味。如果你控制两端,考虑一个序列化框架(Boost Serialization,Google Protobuf ...)

¹ 因为您已经提到序列化 double 等的原始二进制形式

关于c++ - 带有 vector 结构的 boost::asio::buffer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46749607/

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