如何在65536字节上编码二进制数据到C 上的WebSocket帧

How to encode binary data over 65536 bytes to websocket frame on c++

本文关键字:数据 上的 WebSocket 二进制 编码 65536 字节      更新时间:2023-10-16

我的服务器在STD :: String Buffer(ANSI(中保存JPEG-File。我需要应要求将其发送到网络客户。我接下来尝试了:

std::string ws_encode(std::string frame) {
    string result;
    result.resize(2);
    result[0]= 130;
    if (frame.size() <= 125) {result[1]=frame.size();}
    else if (frame.size() >= 126 && frame.size() <= 65535) {
        result.resize(4);
        result[1] = 126;
        result[2] = ( frame.size() >> 8 ) && 255;
        result[3] = ( frame.size() ) && 255;
    }
    else {
        result.resize(10);
        result[1] = 127;
        result[2] = ( frame.size() >> 56 ) && 255;
        result[3] = ( frame.size() >> 48 ) && 255;
        result[4] = ( frame.size() >> 40 ) && 255;
        result[5] = ( frame.size() >> 32 ) && 255;
        result[6] = ( frame.size() >> 24 ) && 255;
        result[7] = ( frame.size() >> 16 ) && 255;
        result[8] = ( frame.size() >>  8 ) && 255;
        result[9] = ( frame.size() ) && 255;
    }
    return result+frame;
}

,然后:

string encoded_frame = ws_encode(Agents["65535"].Screen); // it's a map <string id, struct Agent>, Agent has string Screen buffer for screenshots
send(client_socket, &encoded_frame[0], encoded_frame.size(), 0);

但是,浏览器在没有控制台中没有任何解释的情况下关闭了连接。也许长度计算是错误的,或者并非所有数据都发送了...我不知道 - 在发送看起来正确之前,用编码数据编写test.txt。

有人可以帮助我完成此任务吗?

设置有效载荷长度值的字节时,当您应该使用BITWISE AND(&(运算符时,您将使用LOGICAL AND(&&(运算符。

尝试更多这样的东西:

std::string ws_encode(char opcode, const std::string &data)
{
    string result;
    std::string::size_type size = data.size();
    if (size <= 125)
    {
        result.resize(2+size);
        result[0] = 0x80 | opcode;
        result[1] = (char) size;
    }
    else if (size <= 65535)
    {
        result.resize(4+size);
        result[0] = 0x80 | opcode;
        result[1] = 126;
        result[2] = (size >> 8) & 0xFF;
        result[3] = (size     ) & 0xFF;
    }
    else
    {
        result.resize(10+size);
        result[0] = 0x80 | opcode;
        result[1] = 127;
        result[2] = (size >> 56) & 0xFF;
        result[3] = (size >> 48) & 0xFF;
        result[4] = (size >> 40) & 0xFF;
        result[5] = (size >> 32) & 0xFF;
        result[6] = (size >> 24) & 0xFF;
        result[7] = (size >> 16) & 0xFF;
        result[8] = (size >>  8) & 0xFF;
        result[9] = (size      ) & 0xFF;
    }
    if (size > 0)
    {
        memcpy(&result[result.size()-size], data.c_str(), size);
        // or:
        // std::copy(data.begin(), data.end(), result.begin()+(result.size()-size));
    }
    return result;
}

std::string encoded_frame = ws_encode(0x02, Agents["65535"].Screen);
send(client_socket, encoded_frame.c_str(), encoded_frame.size(), 0);