Last active
January 8, 2023 23:58
-
-
Save antoninkriz/459ca523b377fa8ba63aa4e955f8e959 to your computer and use it in GitHub Desktop.
C# code to quickly send requests to a HTTP server. Can send over ~1500 requests per second to a remote server.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Net; | |
using System.Net.Http.Headers; | |
using System.Text; | |
namespace fastRequests | |
{ | |
internal static class Program | |
{ | |
private const string Host = "example.com"; | |
private const string Url = "https://example.com/"; | |
private const string Ip = "1.2.3.4"; | |
private static readonly HttpMethod TaskType = HttpMethod.Post; | |
private static readonly HttpContent Content = new StringContent( | |
"say=Hello", | |
Encoding.UTF8, | |
"application/x-www-form-urlencoded" | |
); | |
private const int ThreadsCount = 8; | |
private const int ParallelCount = 32; | |
private static readonly UriBuilder WebBuilder = new(Url) | |
{ | |
Host = Ip | |
}; | |
private static readonly HttpClient Client = new(new HttpClientHandler | |
{ | |
UseCookies = false, | |
UseProxy = false, | |
MaxConnectionsPerServer = int.MaxValue, | |
CheckCertificateRevocationList = false, | |
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate | |
}) | |
{ | |
DefaultRequestHeaders = | |
{ | |
Accept = { new MediaTypeWithQualityHeaderValue("text/html") }, | |
Host = Host, | |
Referrer = WebBuilder.Uri | |
} | |
}; | |
private static ulong _requestsCount; | |
private static void Counter() | |
{ | |
var lastCount = 0ul; | |
var watch = new System.Diagnostics.Stopwatch(); | |
watch.Start(); | |
while (true) | |
{ | |
Thread.Sleep(10000); | |
var elapsedMs = watch.ElapsedMilliseconds; | |
watch.Restart(); | |
var currentCount = Interlocked.Read(ref _requestsCount); | |
Console.WriteLine( | |
$"Tasks per second: {(((double)(currentCount - lastCount)) / elapsedMs) * 1000,10:0.000} | Total: {currentCount,15}"); | |
lastCount = currentCount; | |
} | |
} | |
private static void Requester() | |
{ | |
var tasks = new Task<HttpResponseMessage>[ParallelCount]; | |
while (true) | |
{ | |
for (var i = 0; i < ParallelCount; i++) | |
{ | |
tasks[i] = Client.SendAsync( | |
new(TaskType, WebBuilder.Uri) | |
{ | |
Content = Content | |
}, | |
HttpCompletionOption.ResponseContentRead, | |
CancellationToken.None | |
); | |
} | |
Task.WaitAll(tasks); | |
Interlocked.Add(ref _requestsCount, ParallelCount); | |
} | |
} | |
private static void Main() | |
{ | |
new Thread(Counter).Start(); | |
Parallel.For(0, ThreadsCount, _ => Requester()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment