c++ - 尝试通过 tcp 发送 vector

标签 c++ serialization vector tcp

我试图在 C++ 中使用 tcp 发送接收和多维 vector ,但我一直遇到段错误。我试图一次发送一个 vector 而不是单个整数以减少延迟。我想知道我应该如何序列化和反序列化一个 vector (没有像 Boost 这样的库)

服务器:

vector< vector<int> > contours = { {3,6,8}, {7,24,64}, {87,399} };
int len = 3;
int size =0;

while(waitKey(10) != 'q')
{      

    send(new_socket, &len, sizeof(int),0); //send size of vector 

    for(int i =0; i< len; i++){

        size = (contours[i].size() * sizeof(int)) + 24; //byte amount to send and receive

        send(new_socket, &size, sizeof(int), 0);
        send(new_socket, &contours[i], size, 0);
    } 
}

客户:

vector< vector<int> >contours;
vector<int> lines;
int contoursize =0;
int size =0;

while(waitKey(100) != 'q'){

    read(sock,&contoursize, sizeof(int));
    contours.resize(contoursize);

    for(int i =0; i< contoursize; i++){
        read(sock, &size, sizeof(int));


         cout<<" size: "<<size<<endl;

        read(sock, &lines, size);
        contours[i]= lines;
    }
}

最佳答案

send(new_socket, &contours[i], size, 0)你发送实际的std::vector contours[i] 中的对象,你不发送它的数据。还有一个 std::vector object 实际上只是指针和大小的包装器。而且您不能通过网络发送指针。

您需要发送每个 vector 的实际数据:

for (auto const& sub_vector : contours)
{
    // First send the number of elements
    uint32_t number_elements = sub_vector.size();
    send(new_socket, &number_elements, sizeof number_elements, 0);

    // Then send the actual data
    send(new_socket, sub_vector.data(), sub_vector.size() * sizeof sub_vector[0], 0);
}

[省略了错误检查,但你真的应该拥有它。]

我还建议您不要使用像 int 这样的类型,因为它的大小实际上并不固定。如果您想要无符号 32 位整数,请使用 uint32_t .当然你可以用int在您的程序内部,并将数据转换为可移植的固定大小类型以进行传输,只要接收方可以进行相反的转换即可。


此外,我建议您也发送要发送的子 vector 的数量,以便接收方事先知道:

uint32_t number_vectors = contours.size();
send(new_socket, &number_vectors, sizeof number_vectors, 0);

for (...) { ... }

在接收端你可以做类似的事情

// Receive the number of sub-vectors
uint32_t number_vectors;
recv(sock, &number_vectors, sizeof number_vectors, 0);

// Create the vectors
std::vector<std::vector<int>> contours(num_vectors);

// Read all sub-vectors
for (auto& sub_vector : contours)
{
    // Receive the amount of values
    uint32_t number_elements;
    recv(sock, &number_elements, sizeof number_elements, 0);

    // Create the sub-vector
    sub_vector = std::vector<int>(number_elements);

    // Receive the sub-vector data
    recv(sock, sub_vector.data(), sub_vector.size() * sizeof sub_vector[0], 0);
}

[注意:再次省略了错误检查,但应该确实存在。]

关于c++ - 尝试通过 tcp 发送 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55156563/

相关文章:

c++ - 声明为 __attribute__ ((pure)) 的函数是否允许返回新构造的 std::string

C++ 模板特化 - 将其他整数类型委托(delegate)给 uint64_t

json - 为什么反序列化的 TDictionary 无法正常工作?

c++ - vector 存储限制的 vector - 出现 "Microsoft C++ exception: std::bad_alloc at memory location 0x0031650C."错误

c++ - 如何使着色器淡入颜色?

c++ - 为什么不扩展可变参数模板参数包?

c++ - boost 使用 struct 中包含的 typedef 定义的 native 类型的序列化

c++ - 如何将列表序列化为字符数组

c++ - 将 vector<char> buf(256) 转换为 LPCSTR?

R 变量中的变长向量或列表