Advertisement
SteelGolem

simple c# webserver

May 16th, 2015
403
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.34 KB | None | 0 0
  1. /*
  2.  * simple webserver
  3.  * - asynchronous multi-threaded
  4.  * - multiple simultaneous connections
  5.  */
  6.  
  7. using System;
  8. using System.Text;
  9. using System.Net;
  10. using System.IO;
  11.  
  12. namespace ConsoleApplication1
  13. {
  14.     class Program
  15.     {
  16.         static void Main(string[] args)
  17.         {
  18.             HttpListener listener = new HttpListener();
  19.             listener.Prefixes.Add("http://localhost:9999/"); // for testing use, admin not required
  20.             //listener.Prefixes.Add("http://+:9999/"); // for production use, requires admin
  21.             listener.Start();
  22.             listener.BeginGetContext(new AsyncCallback(ProcessRequest), listener);
  23.  
  24.             Console.WriteLine("listening...");
  25.  
  26.             while (listener.IsListening) ; // go FOREVER
  27.  
  28.             // not actually reachable, but your compiler will never know...
  29.             Console.WriteLine("done. press any key to exit.");
  30.             Console.ReadKey();
  31.         }
  32.  
  33.         private static void ProcessRequest(IAsyncResult boxedListener)
  34.         {
  35.             HttpListener listener = (HttpListener)boxedListener.AsyncState;
  36.             HttpListenerContext context = listener.EndGetContext(boxedListener);
  37.             HttpListenerRequest request = context.Request;
  38.             HttpListenerResponse response = context.Response;
  39.  
  40.             // re-use listener to start listening again immediately, it won't interrupt the current request
  41.             listener.BeginGetContext(new AsyncCallback(ProcessRequest), listener);
  42.  
  43.             Console.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]"
  44.                 + " processing request from " + request.RemoteEndPoint + " for " + request.RawUrl);
  45.  
  46.             SendRequestedFile(response);
  47.  
  48.             Console.WriteLine(request.RemoteEndPoint + "'s file sent.");
  49.         }
  50.  
  51.         private static void SendRequestedFile(HttpListenerResponse response)
  52.         {
  53.             Thread.Sleep(3000); // le simulated work to show that long ops are le fine
  54.             string responseString = "<HTML><BODY>Hello world!</BODY></HTML>";
  55.             byte[] buffer = Encoding.UTF8.GetBytes(responseString);
  56.             response.ContentLength64 = buffer.Length;
  57.             Stream outputStream = response.OutputStream;
  58.             outputStream.Write(buffer, 0, buffer.Length);
  59.             outputStream.Close();
  60.         }
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement