Skip to content

Instantly share code, notes, and snippets.

@codemasta92
Created January 19, 2012 09:28
Show Gist options
  • Save codemasta92/1638952 to your computer and use it in GitHub Desktop.
Save codemasta92/1638952 to your computer and use it in GitHub Desktop.
public static void ProcessFrame(FrameType frameType, byte[] data, Action<string> onMessage, Action onClose,
Action<byte[]> onBinary)
{
var encoding = new UTF8Encoding(false, true);
switch (frameType)
{
case FrameType.Close:
if (data.Length == 1 || data.Length>125)
throw new WebSocketException(WebSocketStatusCodes.ProtocolError);
if (data.Length == 2)
{
var closeCode = (uint)data.Take(2).ToArray().ToLittleEndianInt();
if (3000 <= closeCode && closeCode <= 4999)
{
onClose();
break;
}
switch (closeCode)
{
case 1000:
case 1001:
case 1002:
case 1003:
case 1007:
case 1008:
case 1009:
case 1010:
case 1011:
break;
default:
// 1004, 1005, 1006, 1015 are RESERVED codes
throw new WebSocketException(WebSocketStatusCodes.ProtocolError);
}
}
onClose();
break;
case FrameType.Binary:
onBinary(data);
break;
case FrameType.Text:
try
{
var message = encoding.GetString(data);
onMessage(message);
}
catch (ArgumentException)
{
throw new WebSocketException(WebSocketStatusCodes.InvalidFramePayloadData);
}
break;
default:
FleckLog.Debug("Received unhandled " + frameType);
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment