1
size_t getPayloadLength(const unsigned char *inputFrame){
  size_t payloadLength = inputFrame[1] & 0x7F;

  if (payloadLength == 0x7E) {
    uint16_t payloadLength16b = 0;
    memcpy(&payloadLength16b, &inputFrame[2], 2);
    payloadLength = payloadLength16b;

  } else if (payloadLength == 0x7F) {
    uint64_t payloadLength64b = 0;
    memcpy(&payloadLength64b, &inputFrame[2], 8);
    payloadLength = (size_t)payloadLength64b;
  }

  return payloadLength;
}

但是当有效载荷为 == 126 或 127 时,此方法返回错误结果(总是巨大的数字)有人能发现错误吗?

我知道我已经发送了 250 个字符的消息。这是我恢复转换为二进制的前 5 个字节:

[0] 10000001 
[1] 11111110 // & 0x7F = 126 -> so payload length is  byte 2  3 interpreted as 16 bit
[2] 00000000 //
[3] 11111010 // 0000000011111010 = 250 but my function returns 64000
[4] 10001001 
4

1 回答 1

1

您缺少将值从网络字节顺序转换为主机字节顺序的过程。6400011111010 00000000二进制的。您需要使用字节顺序转换例程。

    payloadLength = ntohs(payloadLength16b);

    payloadLength = (size_t)ntohll(payloadLength64b);

如果您的系统缺少定义ntohll,您可以按照此问题的建议答案进行操作。但是,一个可能的实现可能是:

uint64_t ntohll (uint64_t x) {
    const unsigned t = 1;
    if (*(const unsigned char *)&t) {
        x = ((uint64_t)ntohl(x & 0xffffffffU) << 32)
            | ntohl((uint32_t)(x >> 32));
    }
    return x;
}
于 2013-08-14T00:55:47.890 回答