Skip to content

Instantly share code, notes, and snippets.

@Drawaes
Created December 12, 2016 23:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Drawaes/009d39f80ba6caf045b2b8372d4917fa to your computer and use it in GitHub Desktop.
Save Drawaes/009d39f80ba6caf045b2b8372d4917fa to your computer and use it in GitHub Desktop.
ReadableBuffer currentPayload;
int expectedPayloadSize = 0;
while (true)
{
var result = await _lowerConnection.Input.ReadAsync();
var buffer = result.Buffer;
try
{
if (buffer.IsEmpty && result.IsCompleted)
{
new InvalidOperationException("Connection closed before the handshake completed");
}
ReadableBuffer messageBuffer;
TlsFrameType frameType;
while (TryGetFrameType(ref buffer, out messageBuffer, out frameType))
{
//We have a frame,
if(connectionState.IsEncrypted)
{
messageBuffer = Decrypt(ref messageBuffer);
}
//Remove header if it was encrypted the decrypt removed the trailer anyway
messageBuffer = messageBuffer.Slice(5);
if(expectedPayloadSize == 0)
{
expectedPayloadSize = messageBuffer.ReadBigEndian<ushort>();
currentPayload = messageBuffer;
}
else
{
currentPayload.Add(messageBuffer);
}
while(true)
{
if(currentPayload.Length < expectedPayloadSize || expectedPayloadSize == 0)
{
break;
}
var finishedPayload = currentPayload.Slice(0,expectedPayloadSize);
currentPayload = currentPayload.Slice(expectedPayloadSize);
if(currentPayload.Length >= 2)
{
expectedPayloadSize = currentPayload.ReadBigEndian<ushort>();
}
else
{
expectedPayloadSize = 0;
}
ProcessPayload(finishedPayload);
}
}
}
finally
{
_lowerConnection.Input.Advance(buffer.Start, buffer.End);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment