Created
May 19, 2011 02:34
-
-
Save SimonCropp/980071 to your computer and use it in GitHub Desktop.
non blocking client server with httplistener
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; | |
using System.Net; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace ClientConsole | |
{ | |
static class Program | |
{ | |
static void Main() | |
{ | |
//Wait for serer to start | |
Thread.Sleep(1000); | |
Parallel.For(0, 100, i => | |
{ | |
var webRequest = WebRequest.Create("http://localhost:7896/"); | |
webRequest.Headers["thread"] = i.ToString(); | |
using (var webResponse = webRequest.GetResponse()) | |
{ | |
Console.WriteLine(webResponse.Headers["thread"]); | |
} | |
} | |
); | |
Console.ReadLine(); | |
} | |
} | |
} |
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; | |
using System.Diagnostics; | |
using System.Net; | |
using System.Threading; | |
namespace ServerConsole | |
{ | |
static class Program | |
{ | |
static HttpListener listener; | |
static void Main() | |
{ | |
listener = new HttpListener(); | |
listener.Prefixes.Add("http://localhost:7896/"); | |
listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous; | |
listener.Start(); | |
while (true) | |
{ | |
ProcessRequest(); | |
} | |
} | |
static void ProcessRequest() | |
{ | |
var result = listener.BeginGetContext(ListenerCallback, listener); | |
var startNew = Stopwatch.StartNew(); | |
result.AsyncWaitHandle.WaitOne(); | |
startNew.Stop(); | |
Console.WriteLine("ElapsedMilliseconds "+ startNew.ElapsedMilliseconds); | |
} | |
static void ListenerCallback(IAsyncResult result) | |
{ | |
Thread.Sleep(1000); | |
var context = listener.EndGetContext(result); | |
context.Response.StatusCode = 200; | |
context.Response.StatusDescription = "OK"; | |
var s = context.Request.Headers["thread"] + " Received"; | |
Console.WriteLine(s); | |
context.Response.Headers["thread"] = s; | |
context.Response.Close(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment