Created
April 17, 2014 20:12
-
-
Save stanroze/11008822 to your computer and use it in GitHub Desktop.
Simple async HttpListener implementation.
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
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