I have a system that needs to write strings in an HTTP response stream. Each line in this system represents an event, so you can see it as a stream of notifications. I am using .NET4 on Windows 7 using NancyFX and Nancy's own hosting (0.23). The following code is functional:
using System; using System.IO; using System.Threading; using Nancy; using Nancy.Hosting.Self; namespace TestNancy { public class ChunkedResponse : Response { public ChunkedResponse() { ContentType = "text/html; charset=utf-8"; Contents = stream => { using (var streamWriter = new StreamWriter(stream)) { while (true) { streamWriter.WriteLine("Hello"); streamWriter.Flush(); Thread.Sleep(1000); } } }; } } public class HomeModule : NancyModule { public HomeModule() { Get["/"] = args => new ChunkedResponse(); } } public class Program { public static void Main() { using (var host = new NancyHost(new Uri("http://localhost:1234"))) { host.Start(); Console.ReadLine(); } } } }
Now I want to add compression to the stream to compress the amount of bandwidth. For some reason, when testing in the browser, I do not see any result. I tried many combinations to achieve the desired result, but this is what I have at the moment:
using System; using System.IO; using System.IO.Compression; using System.Threading; using Nancy; using Nancy.Hosting.Self; namespace TestNancy { public class ChunkedResponse : Response { public ChunkedResponse() { Headers["Content-Encoding"] = "gzip"; ContentType = "text/html; charset=utf-8"; Contents = stream => { using (var gzip = new GZipStream(stream, CompressionMode.Compress)) using (var streamWriter = new StreamWriter(gzip)) { while (true) { streamWriter.WriteLine("Hello"); streamWriter.Flush(); Thread.Sleep(1000); } } }; } } public class HomeModule : NancyModule { public HomeModule() { Get["/"] = args => new ChunkedResponse(); } } public class Program { public static void Main() { using (var host = new NancyHost(new Uri("http://localhost:1234"))) { host.Start(); Console.ReadLine(); } } } }
I am looking for help that either tells me what I am doing wrong with respect to the HTTP protocol (for example, I tried adding block lengths as described in HTTP1.1, which didn’t work), or helping Nancy where she does something not taken into account .
source share