Skip to content

Instantly share code, notes, and snippets.

@chocoboba
chocoboba / gist:1635265
Created January 18, 2012 20:13
HybiEncode
public byte[] HybiEncode(string message)
{
if (message.Length > 125)
{
message = message.Substring(0, 125);
}
byte[] payload = Encoding.UTF8.GetBytes(message);
List<int> frameHead = new List<int>();
int payloadLength = payload.Length;
@chocoboba
chocoboba / gist:1635232
Created January 18, 2012 20:06
Build WebSocket Handshake
string line = ClientHandshakeLines.FirstOrDefault(l => l.Contains("Sec-WebSocket-Key:"));
if (!string.IsNullOrEmpty(line))
{
Handshake = "HTTP/1.1 101 Switching Protocols" + Environment.NewLine;
Handshake += "Upgrade: websocket" + Environment.NewLine;
Handshake += "Connection: Upgrade" + Environment.NewLine;
Handshake += "Sec-WebSocket-Accept: ";
Handshake += ComputeWebSocketHandshakeSecurityHash09(line.Substring(line.IndexOf(":") + 2));
Handshake += Environment.NewLine;
Handshake += Environment.NewLine;
@chocoboba
chocoboba / gist:1635108
Created January 18, 2012 19:43
HybiDecode
public string HybiDecode(byte[] data)
{
byte firstByte = data[0];
byte secondByte = data[1];
int opcode = firstByte & 0x0F;
bool isMasked = ((firstByte & 128) == 128);
int payloadLength = secondByte & 0x7F;
if (!isMasked) { return null; } // not masked
if (opcode != 1) { return null; } // not text
@chocoboba
chocoboba / gist:1635057
Created January 18, 2012 19:29
Compute WebSocket Hash
public String ComputeWebSocketHandshakeSecurityHash09(String secWebSocketKey)
{
const String MagicKEY = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
String secWebSocketAccept = String.Empty;
// 1. Combine the request Sec-WebSocket-Key with magic key.
String ret = secWebSocketKey + MagicKEY;
// 2. Compute the SHA1 hash
SHA1 sha = new SHA1CryptoServiceProvider();