6

我想知道如何使用 HttpWebRequest 和 HttpWebResponse 读取持久连接。问题似乎是 GetResponseStream() 函数在返回之前等待服务器连接关闭。

是否有另一种简单的方法来读取彗星连接?不起作用的例子。

// get the response stream
        Stream resStream = response.GetResponseStream();

        string tempString = null;
        int count = 0;

        do
        {
            // fill our buffer
            count = resStream.Read(buf, 0, buf.Length);

            // as long as we read something we want to print it
            if (count != 0)
            {
                tempString = Encoding.ASCII.GetString(buf, 0, count);
                Debug.Write(tempString);
            }
        }
        while (true); // any more data to read?
4

1 回答 1

8

如果可以改用WebClient,则几乎没有理由使用HttpWebRequest。看看WebClient.OpenRead 方法。我成功地使用它来读取这样的无限 HTTP 响应:

using (var client = new WebClient())
using (var reader = new StreamReader(client.OpenRead(uri), Encoding.UTF8, true))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}

但是请注意,“长轮询”的目的通常不是发送连续的数据流,而是延迟响应直到发生某些事件,在这种情况下发送响应并关闭连接。所以你所看到的可能只是彗星按预期工作。

于 2010-09-18T17:28:20.030 回答