Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Net;
- using System.Text;
- using System.Threading.Tasks;
- /*
- * Author:
- * Dialog
- *
- * Contact:
- */
- namespace SimpleHttpServer
- {
- public class HttpServer
- {
- private static readonly Random Rand = new Random();
- private readonly HttpListener _listener;
- public HttpServer(int port)
- {
- if (port < 1 || port > ushort.MaxValue)
- throw new ArgumentOutOfRangeException("Port can not be less than 1 or greater than " + ushort.MaxValue);
- _listener = new HttpListener
- {
- Prefixes = { string.Format("http://*:{0}/", port) }
- };
- _listener.Start();
- ListenAsync();
- }
- /// <summary>
- /// Listens for incoming HTTP requests on the specified port
- /// </summary>
- public async Task ListenAsync()
- {
- var context = await _listener.GetContextAsync();
- Console.WriteLine("[{0}]: Received request from {1}",
- DateTime.Now, context.Request.RemoteEndPoint);
- SendResponseAsync(context.Response);
- ListenAsync();
- }
- /// <summary>
- /// Generates a HTML document containing a random number and writes it to the response stream
- /// </summary>
- /// <param name="response">the HttpListenerResponse for the request</param>
- /// <param name="encoding">specifies which encoding should be used. Default is UTF-8</param>
- private static async Task SendResponseAsync(HttpListenerResponse response, Encoding encoding = null)
- {
- var content = string.Format("<html>" +
- "<body>" +
- "<h1>Random number generator</h1>" +
- "<p>The number is: <strong>{0}</strong></p>" +
- "</body>" +
- "</html>", Rand.Next(1000));
- var contentEncoding = encoding ?? Encoding.UTF8;
- var buffer = contentEncoding.GetBytes(content);
- response.ContentLength64 = buffer.Length;
- response.ContentType = "text/html";
- response.ContentEncoding = contentEncoding;
- response.StatusCode = (int) HttpStatusCode.OK;
- using (var stream = response.OutputStream)
- await stream.WriteAsync(buffer, 0, buffer.Length);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment