Nacho
Nacho

Reputation: 99

WebSocket, decoding data frame (c++)

I´m working on a websocket server (in c++) using winsock2. Right now, I´m responding the initial handshake from the client (Chrome in my case) and then I´m sending data from the client:

socket.send("Hello!");

I´m trying to decode the data frame but I´m having a few issues with it. Lets take a look at the code:

int GetBit(const char * data, unsigned int idx)
{
    unsigned int arIdx = idx / 4;
    unsigned int biIdx = idx % 4;
    return (data[arIdx] >> biIdx) & 1;
}

void ParseDataFrame(const char * packet)
{
    int FIN  = GetBit(packet, 0);
    unsigned char OPC = 0;
    {
        int opc0 = GetBit(packet, 4);
        int opc1 = GetBit(packet, 5);
        int opc2 = GetBit(packet, 6);
        int opc3 = GetBit(packet, 7);
        OPC |= (opc0 << 0);
        OPC |= (opc1 << 1);
        OPC |= (opc2 << 2);
        OPC |= (opc3 << 3);
    }  
    int MASK = GetBit(packet, 5);
}

I´m getting:

FIN = 1 
OPC = x6 (can´t be) 
MAKS = 0 (can´t be)

I´ve been reading through the WS Protocol and maybe the problem is in my code. Thanks in advance!

EDIT

I would like to mention that the connection is properly established as there are no errors in the console (chrome) and the socket.onopen event gets called.

Upvotes: 2

Views: 849

Answers (1)

KompjoeFriek
KompjoeFriek

Reputation: 3875

Your data looks OK, the first byte (-127 in dec, or 0x81 or 1000 0001).

When reading with GetBit you use 4 bits per byte in stead of 8.

biIdx currently starts on the most right bit going to the most left bit. This should be the other way around:

int GetBit(const char * data, unsigned int idx)
{
    unsigned int arIdx = idx / 8;
    unsigned int biIdx = idx % 8;
    return (data[arIdx] >> (7 - biIdx)) & 1;
}

That should get you the correct bits.

For the MASK, you should read bit 8. As specified: https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers

Upvotes: 3

Related Questions