SteelGolem icon

simple c# webserver

SteelGolem | PRO | 05/17/15 12:02:25 AM UTC | 0 ⭐ | 672 👁️ | Never ⏰ | []
C# |

2.34 KB

|

None

|

0 👍

/

0 👎

/*
 * simple webserver
 * - asynchronous multi-threaded
 * - multiple simultaneous connections
 */
 
using System;
using System.Text;
using System.Net;
using System.IO;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            HttpListener listener = new HttpListener();
            listener.Prefixes.Add("http://localhost:9999/"); // for testing use, admin not required
            //listener.Prefixes.Add("http://+:9999/"); // for production use, requires admin
            listener.Start();
            listener.BeginGetContext(new AsyncCallback(ProcessRequest), listener);
 
            Console.WriteLine("listening...");
 
            while (listener.IsListening) ; // go FOREVER
 
            // not actually reachable, but your compiler will never know...
            Console.WriteLine("done. press any key to exit.");
            Console.ReadKey();
        }
 
        private static void ProcessRequest(IAsyncResult boxedListener)
        {
            HttpListener listener = (HttpListener)boxedListener.AsyncState;
            HttpListenerContext context = listener.EndGetContext(boxedListener);
            HttpListenerRequest request = context.Request;
            HttpListenerResponse response = context.Response;
 
            // re-use listener to start listening again immediately, it won't interrupt the current request
            listener.BeginGetContext(new AsyncCallback(ProcessRequest), listener);
 
            Console.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]"
                + " processing request from " + request.RemoteEndPoint + " for " + request.RawUrl);
 
            SendRequestedFile(response);
 
            Console.WriteLine(request.RemoteEndPoint + "'s file sent.");
        }
 
        private static void SendRequestedFile(HttpListenerResponse response)
        {
            Thread.Sleep(3000); // le simulated work to show that long ops are le fine
            string responseString = "<HTML><BODY>Hello world!</BODY></HTML>";
            byte[] buffer = Encoding.UTF8.GetBytes(responseString);
            response.ContentLength64 = buffer.Length;
            Stream outputStream = response.OutputStream;
            outputStream.Write(buffer, 0, buffer.Length);
            outputStream.Close();
        }
    }
}

Comments