Tcp协议前缀消息的长度

时间:2018-03-13 19:41:49

标签: c++ node.js

我正在尝试在消息长度前加上4个字节,并在C ++中使用big-endian,但我不明白该怎么做。在Node.JS中,我这样做:

var buffer = new Buffer("HELLO WORLD");

 //create a buffer with +4 bytes
var consolidatedBuffer = new Buffer(4 + buffer.length);

 //write at the beginning of the buffer, the total size
consolidatedBuffer.writeInt32BE(buffer.length, 0);

 //Copy the message buffer to the consolidated buffer at position 4  (after the 4 bytes about the size)

 buffer.copy(consolidatedBuffer, 4);

我试图在C ++中实现相同的结果,但不知道如何做同样的事情,有人可以告诉我在C ++中是如何完成的吗?结果应该是字符串字节数组

我在Mac上这样做:

 std::string data = "HELLO WORLD";

 uint32_t length = htonl( data.length() );

 std::string payload;

 payload.append(std::to_string(length));

 payload.append(data);

1 个答案:

答案 0 :(得分:0)

这样做的一种方法就是

std::vector<char> pack(const std::string& str) {
      const uint32_t sz = str.size();
      const uint32_t n_sz = htonl(sz);
      std::vector<char> result(sizeof(sz) + sz);
      memcpy(result.data(), &n_sz, sizeof(n_sz));
      memcpy(result.data() + sizeof(sz), str.data(), sz);
      return result;
}