c#,blocking,pooled,http,server

Kerim 8/16/2016 0

This Code Shows How to Write a Blocking Pooled HTTP Server

C#
 using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading;

class WebServer
{
  HttpListener _listener;
  string _baseFolder;      // Your web page folder.

  public WebServer (string uriPrefix, string baseFolder)
  {
    System.Threading.ThreadPool.SetMaxThreads (50, 1000);
    System.Threading.ThreadPool.SetMinThreads (50, 50);
    _listener = new HttpListener();
    _listener.Prefixes.Add (uriPrefix);
    _baseFolder = baseFolder;
  }

  public void Start()          // Run this on a separate thread, as
  {                            // we did before.
    _listener.Start();
    while (true)
      try
      {
        HttpListenerContext request = _listener.GetContext();
        ThreadPool.QueueUserWorkItem (ProcessRequest, request);
      }
      catch (HttpListenerException)     { break; }   // Listener stopped.
      catch (InvalidOperationException) { break; }   // Listener stopped.
  }

  public void Stop() { _listener.Stop(); }

  void ProcessRequest (object listenerContext)
  {
    try
    {
      var context = (HttpListenerContext) listenerContext;
      string filename = Path.GetFileName (context.Request.RawUrl);
      string path = Path.Combine (_baseFolder, filename);
      byte[] msg;
      if (!File.Exists (path))
      {
        context.Response.StatusCode = (int) HttpStatusCode.NotFound;
        msg = Encoding.UTF8.GetBytes ("Sorry, that page does not exist");
      }
      else
      {
        context.Response.StatusCode = (int) HttpStatusCode.OK;
        msg = File.ReadAllBytes (path);
      }
      context.Response.ContentLength64 = msg.Length;
      using (Stream s = context.Response.OutputStream)
        s.Write (msg, 0, msg.Length);
    }
    catch (Exception ex) { Console.WriteLine ("Request error: "   ex); }
  }
} 

static void Main() { // Listen on the default port (80), serving files in e:\mydocs\webroot: var server = new WebServer ("http://localhost/", @"e:\mydocs\webroot"); // Start the server on a parallel thread: new System.Threading.Thread (server.Start).Start(); Console.WriteLine ("Server running... press Enter to stop"); Console.ReadLine(); server.Stop(); }

Report Bug

Please Login to Report Bug

Reported Bugs

Comments

Please Login to Comment

Comments