Skip to content

Instantly share code, notes, and snippets.

@stanroze
Created April 17, 2014 20:12
Show Gist options
  • Save stanroze/11008822 to your computer and use it in GitHub Desktop.
Save stanroze/11008822 to your computer and use it in GitHub Desktop.
Simple async HttpListener implementation.
public class SimpleAsyncHost
{
private HttpListener _httpListener;
private bool _stop;
public SimpleAsyncHost()
{
_httpListener = new HttpListener();
_httpListener.Prefixes.Add("http://localhost:10090/");
}
public void Stop()
{
_stop = true;
_httpListener.Stop();
}
public async void ListenAsync()
{
_httpListener.Start();
while (!_stop)
{
HttpListenerContext ctx = null;
try
{
ctx = await _httpListener.GetContextAsync();
}
catch (HttpListenerException ex)
{
if (ex.ErrorCode == 995) return;
}
if(ctx == null) continue;
//got a request
string json = @"{ ""hello"": ""world"" }";
var response = ctx.Response;
response.Headers.Add(HttpResponseHeader.CacheControl, "private, no-store");
response.ContentType = "text/plain";
response.StatusCode = (int) HttpStatusCode.OK;
var messageBytes = Encoding.UTF8.GetBytes(json);
response.ContentLength64 = messageBytes.Length;
await response.OutputStream.WriteAsync(messageBytes, 0, messageBytes.Length);
response.OutputStream.Close();
response.Close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment