c#,http,server

Kerim 8/16/2016 0

This Code Shows How to Write a simple HTTP server

C#
 static void Main()
{
  new System.Threading.Thread (Listen).Start(); // Run server in parallel.
  Thread.Sleep (500);                           // Wait half a second.
  
  using (WebClient wc = new WebClient())        // Make a client request.
    Console.WriteLine (wc.DownloadString     
      ("http://localhost:51111/MyApp/Request.txt"));
}

static void Listen()
{
  HttpListener listener = new HttpListener();
  listener.Prefixes.Add ("http://localhost:51111/MyApp/");  // Listen on
  listener.Start();                                         // port 51111.

  // Wait for a client request:
  HttpListenerContext context = listener.GetContext();

  // Respond to the request:
  string msg = "You asked for: "   context.Request.RawUrl;
  context.Response.ContentLength64 = Encoding.UTF8.GetByteCount (msg);
  context.Response.StatusCode = (int) HttpStatusCode.OK;

  using (Stream s = context.Response.OutputStream)
  using (StreamWriter writer = new StreamWriter (s))
    writer.Write (msg);

  listener.Stop();
} 

Report Bug

Please Login to Report Bug

Reported Bugs

Comments

Please Login to Comment

Comments