Skip to content

Instantly share code, notes, and snippets.

@dotMorten
Created August 25, 2017 21:47
Show Gist options
  • Save dotMorten/f195b4aea93d812574db10d1509c0fcb to your computer and use it in GitHub Desktop.
Save dotMorten/f195b4aea93d812574db10d1509c0fcb to your computer and use it in GitHub Desktop.
Slow webserver response test
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace TimeoutTestApp
{
class Program
{
static void Main(string[] args)
{
SlowHttpServer server = new SlowHttpServer();
server.Start();
ThreadPool.QueueUserWorkItem(async (o) =>
{
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
client.Timeout = TimeSpan.FromSeconds(5); // This has no effect on HttpCompletionOption.ResponseHeadersRead. However it does with ResponseContentRead
var start = DateTime.Now;
//var stream = await client.GetStreamAsync("http://localhost:8080/");
var result = await client.GetAsync("http://localhost:8080/", System.Net.Http.HttpCompletionOption.ResponseHeadersRead); // This would time-out if using ResponseContentRead
var stream = await result.Content.ReadAsStreamAsync();
Console.WriteLine("Headers received...");
int total = 0;
while (stream.CanRead)
{
byte[] buffer = new byte[1024];
total += await stream.ReadAsync(buffer, 0, buffer.Length);
Console.Write($"\rBytes read: {total} - Time elapsed: {Math.Floor((DateTime.Now - start).TotalSeconds).ToString() }s");
}
});
Console.ReadKey();
server.Stop();
}
}
class SlowHttpServer
{
System.Net.HttpListener _listener;
public void Start()
{
_listener = new System.Net.HttpListener();
_listener.Prefixes.Add("http://localhost:8080/");
_listener.Start();
Run();
}
private void Run()
{
ThreadPool.QueueUserWorkItem((o) =>
{
Console.WriteLine("Webserver running...");
try
{
while (_listener.IsListening)
{
ThreadPool.QueueUserWorkItem(async (c) =>
{
var ctx = c as HttpListenerContext;
try
{
ctx.Response.ContentLength64 = 10 * 1024 * 1024;
ctx.Response.StatusCode = 200;
for (int i = 0; i < 10*1024*1024; i++)
{
byte[] buffer = new byte[1];
buffer[0] = (byte)(i % 254 + 1);
ctx.Response.OutputStream.Write(buffer, 0, 1);
ctx.Response.OutputStream.Flush();
await Task.Delay(1);
}
}
catch { } 
                            finally
{
                                ctx.Response.OutputStream.Close();
}
}, _listener.GetContext());
}
}
catch { } 
            });
}
public void Stop()
{
_listener.Stop();
_listener.Close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment