c# - HttpListenerResponse OutputStream.Write 在我的服务器上非常慢

标签 c# linux http mono webserver

我想在我的服务器(Linux 版本 2.6.32-5-vserver-amd64 (Debian 2.6.32-48))上用 C# 设置一个非常基本的网络服务器。
服务器在我的城市,几乎为零的开销功能,例如通过 Apache2 或 Tomcat 8 显示 7 行 html 需要大约 15 毫秒(DNS 1 毫秒,连接 4 毫秒,发送 1 毫秒,等待 6 毫秒,接收 4 毫秒)。
在该服务器上运行我的最小 c# 网络服务器时,接收阶段持续 60 毫秒!
我也在我的本地计算机上使用 .net 框架和单声道尝试了它,最坏的情况下它总是只需要一毫秒。
通过一些测试,我发现如果我不通过 context.Response.OutputStream.Write(...) 发送任何数据,它甚至比 Apache2 或 Tomcat 更快,接收时间降至 0 毫秒!
发送 header 不会使其变慢并且工作正常。
Mono 3.0.6 在服务器上运行,我在 Windows PC 上使用 3.0.6 进行测试。

归结为一个问题:
为什么 OutputStream.Write(...) 在我的服务器上这么慢,我该如何解决?

这是C#代码:

internal class Program
{
    private static void Main(string[] args)
    {
        System.Net.HttpListener listener = new System.Net.HttpListener();
        listener.Prefixes.Add("http://domain.tld:7777/");
        //listener.Prefixes.Add("http://localhost:7777/");
        //listener.Prefixes.Add("http://127.0.0.1:7777/");
        listener.Start();

        while (true)
        {
            System.Net.HttpListenerContext context = listener.GetContext();
            System.Threading.Tasks.Task.Factory.StartNew(() => { ProcessRequest(context); });
        }
    }

    private static void ProcessRequest(System.Net.HttpListenerContext context)
    {
        System.Net.HttpListenerResponse response = context.Response;
        response.ContentType = "text/html";
        byte[] bytes = GetBytes("Testtext");
        response.OutputStream.Write(bytes, 0, bytes.Length); // this line makes the request 60ms slower!
        context.Response.Headers.Add("headerName", "This is the headervalue");
        response.Close();
    }

    private static byte[] GetBytes(string str)
    {
        byte[] bytes = new byte[str.Length * sizeof(char)];
        System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
        return bytes;
    }
}

最佳答案

我找到了解决方案,或者更确切地说是解决方法:
如果我使用

response.Close(bytes, bool); // doesn't matter whether boolean is true or false

并且完全不要写入 Stream 它的速度非常快。对我来说很好,但我还是不明白。

关于c# - HttpListenerResponse OutputStream.Write 在我的服务器上非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24887268/

相关文章:

php - 如何从 POST 请求传递数据?

http - 如何将 "tail"原始 HTTP 请求发送到 Web 应用程序?

c# - Entity Framework (EF) OutOfMemoryException

linux - 如何修改实时文件流

c# - 分割数组的一个元素

python - 同时运行多个 python 文件并在一个完成时终止所有文件

linux - 将数字添加到 find 命令返回的文件列表

javascript - IIS5.1和ASP-classic下HTTP PUT请求的参数检索?

c# - 通过字符串更改属性的状态

c# - Silverlight - 如何本地化对 WCF 服务的调用?