Monday, December 7, 2015

Simple C# Web Server

Simple C# Web Server

using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Net;
using System.Threading;
using System.Diagnostics;
using System.Web;
using System.IO;
using System.Collections.Specialized;
 
namespace SimpleWebServer
{
    public class WebServer
    {
        private readonly HttpListener _listener = new HttpListener();
        private readonly Func<HttpListenerRequest, string> _responderMethod;
 
        public WebServer(string[] prefixes, Func<HttpListenerRequest, string> method)
        {
            if (!HttpListener.IsSupported)
                throw new NotSupportedException(
                    "Needs Windows XP SP2, Server 2003 or later.");
 
            // URI prefixes are required, for example 
            // "http://localhost:8080/index/".
            if (prefixes == null || prefixes.Length == 0)
                throw new ArgumentException("prefixes");
 
            // A responder method is required
            if (method == null)
                throw new ArgumentException("method");
 
            foreach (string s in prefixes)
                _listener.Prefixes.Add(s);
 
            _responderMethod = method;
            _listener.Start();
        }
 
        public WebServer(Func<HttpListenerRequest, string> method, params string[] prefixes)
            : this(prefixes, method) { }
 
        public void Run()
        {
            ThreadPool.QueueUserWorkItem((o) =>
            {
                Console.WriteLine("Webserver running...");
                try
                {
                    while (_listener.IsListening)
                    {
                        ThreadPool.QueueUserWorkItem((c) =>
                        {
                            var ctx = c as HttpListenerContext;

                            Debug.WriteLine("RAW URL: " + ctx.Request.RawUrl );
                            //Debug.WriteLine("VAR1: " + ctx.Request.QueryString["var1"]);

                            string input = null;

                            if (ctx.Request.HttpMethod == "POST")
                            {
                                using (StreamReader reader = new StreamReader(ctx.Request.InputStream))
                                {
                                    input = reader.ReadToEnd();
                                }

                            }
                            else if (ctx.Request.HttpMethod == "GET")
                            {
                                input = listenerRequest.Url.QueryString;
                            }

                            NameValueCollection coll = HttpUtility.ParseQueryString(input);

                            foreach (String s in coll.AllKeys)
                            {
                                Debug.WriteLine(s + ": " + coll[s]);
                            }

                            try
                            {
                                string rstr = _responderMethod(ctx.Request);
                                byte[] buf = Encoding.UTF8.GetBytes(rstr);
                                ctx.Response.ContentLength64 = buf.Length;
                                ctx.Response.OutputStream.Write(buf, 0, buf.Length);
                            }
                            catch { } // suppress any exceptions
                            finally
                            {
                                // always close the stream
                                ctx.Response.OutputStream.Close();
                            }
                        }, _listener.GetContext());
                    }
                }
                catch { } // suppress any exceptions
            });
        }
 
        public void Stop()
        {
            _listener.Stop();
            _listener.Close();
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        WebServer ws = new WebServer(SendResponse, "http://localhost:8080/test/");
        ws.Run();
        Console.WriteLine("A simple webserver. Press a key to quit.");
        Console.ReadKey();
        ws.Stop();
    }
 
    public static string SendResponse(HttpListenerRequest request)
    {
        return string.Format("<HTML><BODY>My web page.<br>{0}</BODY></HTML>", DateTime.Now);    
    }
}

Another one:

C# WebServer - http://webserver.codeplex.com/

Reference:

https://codehosting.net/blog/BlogEngine/post/Simple-C-Web-Server.aspx

http://stackoverflow.com/questions/1767549/is-there-a-net-ready-made-method-to-process-response-body-of-a-httplistener-htt

No comments: