问题描述
我遇到了代理HTTP流的问题.
I have run to a problem with Proxying http stream.
首先:我正在使用VLC播放器创建http协议媒体流服务器.
First: I am creating http protocol media streaming server with VLC player.
第二:我正在使用HttpListener侦听一个端口上的http请求,并尝试转发来自vlc服务器端口的响应作为来自第一个请求的响应.
Second: I'm listening http requests on one port with HttpListener and trying to forward response from vlc server port as a response from first one.
代理:
Client Server(:1234) VLC(:2345)
-request-> HttpListener
HttpWebRequest -request->
HttpWebResponse <-response-
Stream <=Copy= Stream
<-response- HttpListenerResponse
一切正常.但是仍然存在一个问题.我正在尝试将实时流复制到HttpListenerResponse.但是我不能在其属性ContentLength64上附加负值. HttpWebResponse ContentLength属性的值为-1.它应该是内容的无限长度的值.
Everything works fine. But still there is one problem. I am trying to copy live stream to HttpListenerResponse. But I can't append negative value to its property ContentLength64. HttpWebResponse ContentLength property has value of -1. It should be the value for infinite length of content.
这是必需的,因为我正在转发实时流.
This is needed because I'm forwarding live stream.
void ProxyRequest(HttpListenerResponse httpResponse)
{
HttpWebRequest HttpWReq = (HttpWebRequest)WebRequest.Create("http://localhost:2345");
HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
// this must be >=0. Throws ArgumentOutOfRangeException "The value specified for a set operation is less than zero."
httpResponse.ContentLength64 = HttpWResp.ContentLength;
byte[] buffer = new byte[32768];
int bytesWritten = 0;
while (true)
{
int read = HttpWResp.GetResponseStream().Read(buffer, 0, buffer.Length);
if (read <= 0)
break;
httpResponse.OutputStream.Write(buffer, 0, read);
bytesWritten += read;
}
}
有人对此问题有解决方案吗?
Does anyone have a solution for this problem?
推荐答案
将SendChunked属性设置为true并删除ContentLength64值分配是解决方案.就像您提供的链接中所述.
Setting SendChunked property to true and removing ContentLength64 value assigning should be the solution. Like it's described in your provided link.
void ProxyRequest(HttpListenerResponse httpResponse)
{
HttpWebRequest HttpWReq = (HttpWebRequest)WebRequest.Create("http://localhost:2345");
HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
// Solution!!!
httpResponse.SendChunked = true;
byte[] buffer = new byte[32768];
int bytesWritten = 0;
while (true)
{
int read = HttpWResp.GetResponseStream().Read(buffer, 0, buffer.Length);
if (read <= 0)
break;
httpResponse.OutputStream.Write(buffer, 0, read);
bytesWritten += read;
}
}
这篇关于HttpListenerResponse及其ContentLength64属性的无穷大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!