简体   繁体   中英

C++ - Unable to get prefixed uint16_t header

Here is how I form up my message with FlatBuffers and how I send it over via Boost ASIO.

enum ServerOpcode : uint16_t{
    SMSG_AUTH_CONNECTION_RESPONSE                    = 0x001,
    SMSG_LOGIN_REQUEST                               = 0x002,
    SMSG_LOGIN_REQUEST_RESPONSE_TEST                 = 0xA99,
};

ServerOpcode opc;
opc = ServerOpcode::SMSG_LOGIN_REQUEST_RESPONSE_TEST;

flatbuffers::FlatBufferBuilder builder;
auto email = builder.CreateString("test@abv.bg");
auto password = builder.CreateString("passHerepassHerepassHerepassHereZzpa");
auto loginRequest = Vibranium::CreateLoginRequest(builder,email,password);
builder.FinishSizePrefixed(loginRequest);
size_t size = builder.GetSize();
uint8_t *buf = builder.GetBufferPointer();

uint8_t *actualBuffer = new uint8_t[size + 2];
actualBuffer[1] = (opc >> 8);
actualBuffer[0] = (opc&0xFF);
memcpy(actualBuffer + 2, buf, size);


boost::asio::write(s, boost::asio::buffer(actualBuffer,size + 2));

So what I basically want to achieve is to prepend a uint16_t header infront of the flatbuffers message.

Here is the structure I use.

class Packet {
public:
    Packet()
    {
    }
    static const int header_size = 2;
    static const int body_size_in_bytes = 4;
    std::vector<std::byte> header_buffer;
    std::vector<std::byte> size_buffer;
    uint16_t headerCode{0};
    uint32_t body_size{0};
    std::vector<std::byte> body_buffer;
    void PreparePacket(ServerOpcode serverOpcode, std::string message);
};

And here is how I try to read the header on server side:

void Vibranium::Client::read_header() {
    auto self(shared_from_this());
    _packet.header_buffer.resize(_packet.header_size);
    boost::asio::async_read(socket,
    boost::asio::buffer(_packet.header_buffer.data(), _packet.header_size),
    [this, self](boost::system::error_code ec,std::size_t bytes_transferred)
    {
        if ((boost::asio::error::eof == ec) || (boost::asio::error::connection_reset == ec))
        {
            Disconnect();
        }
        else
        {
            std::memcpy(&_packet.header_buffer, &_packet.header_buffer[0], sizeof (_packet.headerCode));
            std::cout << "Header Code: " << _packet.headerCode << std::endl;
            //read_size();
        }
    });
}

Unfortunately this gives me output of:

Header Code: 0

Why and how can I get the prepended 2 byte header correctly? Where is my mistake and how can I fix it?

There is a mistake in your 'copy step', you are copying from source to target. (The compiler might actually notify you of that).

If you change your memcpy to std::memcpy(&_packet.headerCode, &_packet.header_buffer[0], sizeof (_packet.headerCode)); , it should start working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM