HttpListenerResponse和其ContentLength64属性的无限值

本文关键字:无限 属性 和其 ContentLength64 HttpListenerResponse | 更新日期: 2023-09-27 18:14:44

我遇到了代理http流的问题。

首先:我正在创建带有VLC播放器的http协议流媒体服务器。

第二:我在一个端口上监听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;
    }
}
谁有解决这个问题的办法?

HttpListenerResponse和其ContentLength64属性的无限值

设置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;
    }
}