using System; using System.Net; using System.IO; namespace NetCoreServer { /// /// HTTP server is used to create HTTP Web server and communicate with clients using HTTP protocol. It allows to receive GET, POST, PUT, DELETE requests and send HTTP responses. /// /// Thread-safe. public class HttpServer : TcpServer { /// /// Initialize HTTP server with a given IP address and port number /// /// IP address /// Port number public HttpServer(IPAddress address, int port) : base(address, port) { Cache = new FileCache(); } /// /// Initialize HTTP server with a given IP address and port number /// /// IP address /// Port number public HttpServer(string address, int port) : base(address, port) { Cache = new FileCache(); } /// /// Initialize HTTP server with a given DNS endpoint /// /// DNS endpoint public HttpServer(DnsEndPoint endpoint) : base(endpoint) { Cache = new FileCache(); } /// /// Initialize HTTP server with a given IP endpoint /// /// IP endpoint public HttpServer(IPEndPoint endpoint) : base(endpoint) { Cache = new FileCache(); } /// /// Get the static content cache /// public FileCache Cache { get; } /// /// Add static content cache /// /// Static content path /// Cache prefix (default is "/") /// Cache filter (default is "*.*") /// Refresh cache timeout (default is 1 hour) public void AddStaticContent(string path, string prefix = "/", string filter = "*.*", TimeSpan? timeout = null) { timeout ??= TimeSpan.FromHours(1); bool Handler(FileCache cache, string key, byte[] value, TimeSpan timespan) { var response = new HttpResponse(); response.SetBegin(200); response.SetContentType(Path.GetExtension(key)); response.SetHeader("Cache-Control", $"max-age={timespan.Seconds}"); response.SetBody(value); return cache.Add(key, response.Cache.Data, timespan); } Cache.InsertPath(path, prefix, filter, timeout.Value, Handler); } /// /// Remove static content cache /// /// Static content path public void RemoveStaticContent(string path) { Cache.RemovePath(path); } /// /// Clear static content cache /// public void ClearStaticContent() { Cache.Clear(); } protected override TcpSession CreateSession() { return new HttpSession(this); } #region IDisposable implementation // Disposed flag. private bool _disposed; protected override void Dispose(bool disposingManagedResources) { if (!_disposed) { if (disposingManagedResources) { // Dispose managed resources here... Cache.Dispose(); } // Dispose unmanaged resources here... // Set large fields to null here... // Mark as disposed. _disposed = true; } // Call Dispose in the base class. base.Dispose(disposingManagedResources); } // The derived class does not have a Finalize method // or a Dispose method without parameters because it inherits // them from the base class. #endregion } }