using System.Net; using System.Text; public class PdfWebViewer { private HttpListener? _listener; private const string _url = "http://localhost:8000/"; private Thread? _serverThread; private bool _runServer = true; public async void HandleIncomingConnections() { try { Console.WriteLine("Listening for connections on {0}", _url); // While a user hasn't visited the `shutdown` url, keep on handling requests while (_runServer) { try { if (_listener is null) return; // Will wait here until we hear from a connection var ctx = await _listener.GetContextAsync(); // Peel out the requests and response objects var req = ctx.Request; var resp = ctx.Response; // Write the response info try { var splitPath = req.Url!.AbsolutePath.Trim('/'); await using var viewerDataStream = await FileSystem.Current.OpenAppPackageFileAsync(splitPath); var ext = Path.GetExtension(req.Url.AbsolutePath); string contentType = ext.Trim('.') switch { "html" => "text/html", "js" => "application/x-javascript", "css" => "text/css", // ReSharper disable once StringLiteralTypo "bcmap" => "application/octet-stream", "svg" => "image/svg+xml", "png" => "image/png", "json" => "application/json", "jpg" => "image/jpeg", "jpeg" => "image/jpeg", "gif" => "image/gif", _ => "text/plain" }; bool asText = ext.Trim('.') switch { "html" => true, "js" => true, "css" => true, "json" => true, _ => false }; byte[] data; if (asText) { using var streamReader = new StreamReader(viewerDataStream); var pageData = await streamReader.ReadToEndAsync(); data = Encoding.UTF8.GetBytes(pageData); resp.ContentEncoding = Encoding.UTF8; } else { int read = 0; byte[] buffer = new byte[1024]; var readBytes = new List(); while ((read = await viewerDataStream.ReadAsync(buffer, 0, buffer.Length)) > 0) { readBytes.AddRange(buffer.Take(read)); } data = readBytes.ToArray(); } resp.ContentType = contentType; resp.ContentLength64 = data.LongLength; // Write out to the response stream (asynchronously), then close it await resp.OutputStream.WriteAsync(data); } catch (Exception ex) { Console.WriteLine($"Could not find file: {ex}"); resp.ContentType = "text/plain"; resp.StatusCode = (int)HttpStatusCode.NotFound; var data = Encoding.UTF8.GetBytes(ex.ToString()); resp.ContentEncoding = Encoding.UTF8; resp.ContentLength64 = data.LongLength; await resp.OutputStream.WriteAsync(data); } resp.Close(); } catch (Exception ex) { Console.WriteLine(ex); } } } catch (Exception ex) { Console.WriteLine(ex); } } public void Run() { // Create an Http server and start listening for incoming connections _listener = new HttpListener(); _listener.Prefixes.Add(_url); _listener.Start(); _serverThread = new Thread(new ThreadStart(HandleIncomingConnections)); _serverThread.Start(); } public void Stop() { _runServer = false; _listener.Stop(); try { _serverThread.Join(); } catch { } } }