Decoding binary #WebSockets data using C#

On some websites, you may notice data being exchanged between server and client, with no evident Ajax calls being made, in which case there may be activity on the WebSockets (WS) channel, and in this channel, if you are greeted by a jumble of binary data, then you may feel like giving up, but you may find it is easier to decode than you think.

The first clue I noticed was that there was a request header called

Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits

Where deflate is a compression mechanism, which is similar to GZip, and can be decoded easily in C#, First step, though is to view the binary data as base64, so you can copy & paste it, then using this function;

public static byte[] Decompress(byte[] data)
{
MemoryStream input = new MemoryStream(data);
MemoryStream output = new MemoryStream();
using (DeflateStream dstream = new DeflateStream(input, CompressionMode.Decompress))
{
dstream.CopyTo(output);
}
return output.ToArray();
}

Which is called as follows;

var binInput = Convert.FromBase64String(b64Input);
var bDeflate = Decompress(binInput);
var output = Encoding.UTF8.GetString(bDeflate);

And from there, you see much more familiar JSON text.

Leave a Reply

Your email address will not be published.