【问题标题】:Trying to send vector over tcp试图通过 tcp 发送向量
【发布时间】:2019-03-14 06:54:23
【问题描述】:

我试图在 c++ 中使用 tcp 发送接收和多维向量,但我不断收到分段错误。我试图一次发送一个向量而不是单个整数以减少延迟。我想知道我应该如何序列化和反序列化一个向量(没有任何像 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;
    }
}

【问题讨论】:

  • read(sock, &amp;lines, size); - 您正在覆盖 vector 本身的结构,而不是读入它保存的缓冲区。但是你为什么不想使用图书馆呢?标准库没有提供任何适当的序列化机制,因此使用其他一些广泛使用的库是正确的做法。
  • 为什么是+24?而且你不能只是将随机数据读入一个对象。您必须发送 contents 并读入内容。这就是为什么它可能会爆炸

标签: c++ serialization vector tcp


【解决方案1】:

使用send(new_socket, &amp;contours[i], size, 0),您在contours[i] 中发送实际的std::vector 对象,您不会发送它的数据。 std::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,将数据转换成可移植的固定大小类型进行传输,只要接收端可以做相反的转换即可。


另外我建议你也发送你要发送的子向量的数量,以便接收方事先知道:

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);
}

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

【讨论】:

    猜你喜欢
    • 2014-01-16
    • 2016-02-20
    • 1970-01-01
    • 1970-01-01
    • 2018-10-24
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    相关资源
    最近更新 更多