Reputation: 1109
How do you decode a continuation frame in websocket? Can someone please give me a useful insights into this? Decoding a continuation frame as text frame results in error.
I'm sending a large text-string to the server and I can manage to decode only the first incoming text frame and fails after that.
Here is a simple function in nodejs that handles the text frame decoding -
function decodeWS(data)
{
var dl = data[1] & 127;
var ifm = 2;
if (dl == 126)
{
ifm = 4;
} else if (dl == 127)
{
ifm = 10;
}
var i = ifm + 4;
var masks = data.slice(ifm,i);
var index = 0;
var output = "";
var l=data.length;
while (i < l)
{
output += String.fromCharCode(data[i++] ^ masks[index++ % 4]);
}
return output;
}
Upvotes: 2
Views: 2951
Reputation: 3545
Get specific Frame bits
bool fin = (data[0] & 128) == 128;
int opCode = data[0] & 15;
bool isMasked = (data[1] & 128) == 128;
int dataLength = data[1] & 127;
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-------+-+-------------+-------------------------------+
|F|R|R|R| opcode|M| Payload len | Extended payload length |
|I|S|S|S| (4) |A| (7) | (16/64) |
|N|V|V|V| |S| | (if payload len==126/127) |
| |1|2|3| |K| | |
+-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
| Extended payload length continued, if payload len == 127 |
+ - - - - - - - - - - - - - - - +-------------------------------+
| |Masking-key, if MASK set to 1 |
+-------------------------------+-------------------------------+
| Masking-key (continued) | Payload Data |
+-------------------------------- - - - - - - - - - - - - - - - +
: Payload Data continued ... :
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
| Payload Data continued ... |
+---------------------------------------------------------------+
Example: Getting the FIN Bit
First of all write down the binary representation of the first byte, lets pretend the first bit is 130
, so 1000 0010
in Binary or more understandable Fin bit set and opCode 2 for Binary Data.
If you want the get the most significant bit you need to use the logical AND (&) operator with 128
(1000 0000
in Binary).
So basically 1 and 1 will be 1, everything else will be 0.
1000 0010 -> First Byte
1000 0000 -> Our Masking Byte => 128 in Decimal
---------
1000 0000 -> Resulting Byte => 128 in Decimal (Fin bit set)
Another Example Fin bit not set and Text Data.
0000 0001 -> First Byte
1000 0000 -> Our Masking Byte -> 128 in Decimal
---------
0000 0000 -> Resulting Byte => 0 in Decimal (Fin bit not set)
Example: Getting OpCode (OpCode tells you what this frame is used for)
The OpCode can be gathered from the first 4 bits of the first byte. Pretend the FIN bit is set and the OpCode is Text.
1000 0001 -> First Byte
0000 1111 -> Our Masking Byte => 15 in Decimal
---------
0000 0001 -> Resulting Byte => 1 in Decimal (Text OpCode)
Upvotes: 6