private void TryProcessMessage(MqttConnection connection, SocketAsyncEventArgs receiveSendEventArgs) { var lastProcessedByteByCompleteMessage = -1; var remainingBytesToProcess = connection.PreviouslyReceivedBytes + receiveSendEventArgs.BytesTransferred; var bufferOffset = connection.ReceiveSocketOffset; while (remainingBytesToProcess > 0) { try { var messageType = GetMessageType( receiveSendEventArgs.Buffer, ref bufferOffset, ref remainingBytesToProcess); var payloadLength = GetPayloadLength( receiveSendEventArgs.Buffer, ref bufferOffset, ref remainingBytesToProcess); if (payloadLength <= remainingBytesToProcess) { var rawMessage = rawMessageFactory.CreateRawMessageWithData( connection, messageType, receiveSendEventArgs.Buffer, bufferOffset, payloadLength); connection.EnqueueRawMessage(rawMessage); bufferOffset += payloadLength; remainingBytesToProcess -= payloadLength; lastProcessedByteByCompleteMessage = bufferOffset - connection.ReceiveSocketOffset; } else { throw new AggregateException(); } } catch (AggregateException) { var totalUnprocessedBytes = connection.PreviouslyReceivedBytes + receiveSendEventArgs.BytesTransferred - lastProcessedByteByCompleteMessage; if (lastProcessedByteByCompleteMessage > 0) { Buffer.BlockCopy( receiveSendEventArgs.Buffer, connection.ReceiveSocketOffset + lastProcessedByteByCompleteMessage, receiveSendEventArgs.Buffer, connection.ReceiveSocketOffset, totalUnprocessedBytes); } receiveSendEventArgs.SetBuffer( connection.ReceiveSocketOffset + totalUnprocessedBytes, connection.ReceiveSocketBufferSize - totalUnprocessedBytes); connection.PreviouslyReceivedBytes = totalUnprocessedBytes; return; } } receiveSendEventArgs.SetBuffer(connection.ReceiveSocketOffset, connection.ReceiveSocketBufferSize); }