通过处理程序 ASP.NET 将文本流式传输到客户端

发布于 2024-11-04 22:27:43 字数 1012 浏览 2 评论 0原文

为了解决 Twitter 流 API 没有跨域文件来从客户端访问它的问题(在本例中为 Silverlight),我在一个 Web 项目中创建了一个通用处理程序文件,该文件基本上从 twitter 下载流,并在读取流时将其写入客户。 这是处理程序代码:

 context.Response.Buffer = false;
        context.Response.ContentType = "text/plain";

        WebRequest request = WebRequest.Create("http://stream.twitter.com/1/statuses/filter.json?locations=-180,-90,180,90");
        request.Credentials = new NetworkCredential("username", "password");
        StreamReader responseStream = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.GetEncoding("utf-8"));

        while (!responseStream.EndOfStream)
        {
                string line = "(~!-/" + responseStream.ReadLine() + "~!-/)";
               context.Response.BinaryWrite((Encoding.UTF8.GetBytes(line)));}

这确实有效,但问题是一旦客户端断开连接,处理程序就会继续下载。那么如何判断客户端是否仍在忙于接收请求,如果不是,则结束 while 循环?

另外,我的第二个问题是,在客户端执行“ReadLine()”不会执行任何操作,大概是因为它将整个流计为一行,因此永远不会得到完整的响应。为了解决这个问题,我逐字节读取它,当它看到“(~!-/”周围的东西时,它知道这是一行。我知道,非常hacky。

谢谢!

To get around twitters streaming API not having a crossdomain file to access it from client side( in this case Silverlight) I have made a Generic Handler file in a web project which basically downloads the stream from twitter and as it reads it, writes it to the client.
Here is the handler code:

 context.Response.Buffer = false;
        context.Response.ContentType = "text/plain";

        WebRequest request = WebRequest.Create("http://stream.twitter.com/1/statuses/filter.json?locations=-180,-90,180,90");
        request.Credentials = new NetworkCredential("username", "password");
        StreamReader responseStream = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.GetEncoding("utf-8"));

        while (!responseStream.EndOfStream)
        {
                string line = "(~!-/" + responseStream.ReadLine() + "~!-/)";
               context.Response.BinaryWrite((Encoding.UTF8.GetBytes(line)));}

And this does work, but the problem is that once the client disconnects the handler just carry's on downloading. So how do I tell if the client is still busy receiving the request and if not, end the while loop?

Also, my second problem is that on the client side doing a "ReadLine()" does nothing, presumably because it is counting the entire stream as one line so never gets the full response. To work around that I read it byte by byte and when it sees "(~!-/" around something it know that is one line. VERY hacky, I know.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深爱成瘾 2024-11-11 22:27:43

找到答案了!

while (context.Response.IsClientConnected)

:)

Found the answer!

while (context.Response.IsClientConnected)

:)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文