我在代理 http 流时遇到了问题。
首先:我正在使用 VLC 播放器创建 http 协议(protocol)媒体流服务器。
第二:我正在使用 HttpListener 在一个端口上监听 http 请求,并尝试将来自 vlc 服务器端口的响应转发为第一个端口的响应。
代理:
Client Server(:1234) VLC(:2345)
-request-> HttpListener
HttpWebRequest -request->
HttpWebResponse <-response-
Stream <=Copy= Stream
<-response- HttpListenerResponse
一切正常。但仍然存在一个问题。我正在尝试将实时流复制到 HttpListenerResponse。但我无法为其属性 ContentLength64 附加负值。 HttpWebResponse ContentLength 属性的值为 -1。它应该是无限长度内容的值。
这是必需的,因为我正在转发直播。
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;
}
}
有人能解决这个问题吗?
最佳答案
将 SendChunked 属性设置为 true 并删除 ContentLength64 值分配应该是解决方案。就像您提供的链接中所描述的那样。
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;
}
}
关于c# - HttpListenerResponse 及其 ContentLength64 属性的无限值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8115422/