C# HttpWebResponse Comet problem

风格不统一 提交于 2019-11-30 05:15:32

问题


I am wondering how I would go about reading a persistent connection with HttpWebRequest and HttpWebResponse. The problem seems to be that the GetResponseStream() function waits for the server connection to be closed before returning.

Is there an alternative easy way to read a comet connection? Example that doesn't work.

// 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?

回答1:


There is little reason to use HttpWebRequest if you can use WebClient instead. Have a look at the WebClient.OpenRead Method. I'm successfully using it to read from an infinite HTTP response like this:

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);
    }
}

Note, however, that the point of "long-polling" is usually not to send a continuous stream of data, but to delay the response until some event occurs, in which case the response is sent and the connection closed. So what you're seeing might simply be Comet working as intended.



来源:https://stackoverflow.com/questions/3742631/c-sharp-httpwebresponse-comet-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!