我想每次发送长度可变的数据包。我的开发过程如下所示,引用了here。正如我预期的那样,它发送聚合数据的长度和数据本身的总和,然后客户端应划分两个值。在这里,长度的大小是固定长度,因此我可以找出客户端中的数据大小。但是客户未能正确划分第二个。
std::stringstream buffer;
msgpack::pack(buffer, d);
buffer.seekg(0);
std::string str(buffer.str());
int size = str.size();
// to fixed length
// http://forums.devshed.com/programming-42/novice-question-socket-recv-variable-buf-size-592435.html
char c_size[10];
sprintf(c_size, "%d", size);
std::stringstream buffer_of_size;
msgpack::pack(buffer_of_size, c_size);
buffer_of_size.seekg(0);
std::string str_size(buffer_of_size.str());
std::cout << "size of str :: " << str.size() << std::endl;
std::cout << "size of str_size :: " << str_size.size() << std::endl;
char* total_data_pointer = (char*)malloc(str.size() + str_size.size());
memcpy(total_data_pointer, str_size.data(), str_size.size());
memcpy(total_data_pointer + str_size.size(), str.data(), str.size());
if (send(s, total_data_pointer, str.size() + str_size.size(), 0) < 0)
{
puts("Send failed");
return -1;
}
puts("Data Send\n");
客户端: 我只是将收集数据包的部分附加了两次。
c_size = connection.recv(7)
size_data = umsgpack.unpackb(c_size)
print('data size : {}'.format(size_data))
data = connection.recv(int(size_data))
# print(sys.stderr, 'received "%s"' % data)