【发布时间】:2014-10-10 13:41:45
【问题描述】:
我有一个系统应该将行写入 HTTP 响应流。该系统中的每一行都代表某种事件,因此您可以将其视为通知流。我在使用 NancyFX 和 Nancy 自托管 (0.23) 的 Windows 7 上使用 .NET4。以下代码是有效的:
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();
}
}
}
}
现在我想对流添加压缩以压缩带宽量。出于某种原因,在浏览器中进行测试时,我看不到任何结果。我尝试了很多组合来达到预期的效果,但这就是我目前所拥有的:
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();
}
}
} }
我正在寻求帮助,要么告诉我我在 HTTP 协议方面做错了什么(例如,我尝试按照 HTTP1.1 中的描述添加块长度,但没有奏效),或者关于 Nancy 的帮助没有考虑。
【问题讨论】:
-
使用 NancyFx 自托管,您会使用 HttpListener 对吗?通常,如果您在写入内容之前省略内容长度,则内容将作为分块发送而无需进一步干预。我不知道南希在写作之前做了什么魔法,所以这可能是相关的,也可能是不相关的。
标签: c# .net http hosting nancy