C#的HttpWebResponse彗星问题 [英] C# HttpWebResponse Comet problem

查看:147
本文介绍了C#的HttpWebResponse彗星问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道我怎么会去阅读与HttpWebRequest和HttpWebResponse持久连接。这个问题似乎是该GetResponseStream()函数等待服务器连接在返回前关闭。

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

  //得到响应流
        流resStream = response.GetResponseStream();

        字符串tempString = NULL;
        诠释计数= 0;

        做
        {
            //填补了我国缓冲区
            数= resStream.Read(BUF,0,buf.Length);

            //只要我们读的东西,我们要打印出来
            如果(计数!= 0)
            {
                tempString = Encoding.ASCII.GetString(BUF,0,计数);
                Debug.Write(tempString);
            }
        }
        而(真); //更多的数据读取?
 

解决方案

没有什么理由使用的 HttpWebRequest的如果你可以使用的WebClient 代替。看一看在 WebClient.OpenRead方法。我成功地使用它从这样一个无限的HTTP响应为:

 使用(VAR的客户=新的Web客户端())
使用(VAR读卡器=新的StreamReader(client.OpenRead(URI),Encoding.UTF8,真))
{
    串线;
    而((行= reader.ReadLine())!= NULL)
    {
        Console.WriteLine(线);
    }
}
 

注意下,然而,长轮询的点通常是不发送数据的连续流,而是直到某些事件发生时延迟响应,在这种情况下,反应是发送和关闭连接。所以,你看到的可能只是彗星如预期。

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?

解决方案

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.

这篇关于C#的HttpWebResponse彗星问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆