public
Last active

HttpListener Example

  • Download Gist
HttpListenerExample.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
using System;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
 
namespace Server
{
public static class Program
{
private static void IgnoreFailure(Action a)
{
try
{
a();
}
// ReSharper disable EmptyGeneralCatchClause
catch
// ReSharper restore EmptyGeneralCatchClause
{
}
}
 
public static void Main(string[] args)
{
const int numConcurrent = 4;
IgnoreFailure(() =>
{
using (var hl = new HttpListener())
{
var tasks = new Task[numConcurrent];
var cts = new CancellationTokenSource();
 
try
{
hl.Prefixes.Add("http://+:3333/test/");
hl.Start();
}
catch (Exception ex)
{
Console.WriteLine(ex);
Environment.Exit(-1);
}
for (var i = 0; i < tasks.Length; ++i)
{
Start(tasks, i, cts.Token, hl);
}
Console.WriteLine("Press any key to stop server.");
Console.ReadKey();
cts.Cancel();
foreach (var t in tasks)
{
t.Wait(TimeSpan.FromSeconds(30));
}
hl.Stop();
}
}
);
}
 
private static void Start(Task[] tasks, int i, CancellationToken token, HttpListener hl)
{
tasks[i] =
hl
.GetContextAsync()
.ContinueWith(ProcessRequest, token)
.ContinueWith(_ => Start(tasks, i, token, hl), token);
}
 
private static void ProcessRequest(Task<HttpListenerContext> task)
{
IgnoreFailure(() =>
{
if (!task.IsCompleted)
return;
var ctx = task.Result;
var filename =
ctx.Request.Url.AbsolutePath.ToLowerInvariant()
.Split('/')
.SkipWhile(x => x != "test")
.Skip(1)
.First()
;
var buffer = Encoding.UTF8.GetBytes(filename);
ctx.Response.ContentType = "text/plain";
ctx.Response.OutputStream.Write(buffer, 0, buffer.Length);
ctx.Response.Close();
}
);
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.