HttpListenerResponse and infinite value for its Co

2019-08-06 16:49发布

问题:

I have run to a problem with Proxying http stream.

First: I am creating http protocol media streaming server with VLC player.

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.

Proxy:

Client            Server(:1234)                         VLC(:2345)
       -request-> HttpListener
                  HttpWebRequest           -request->
                  HttpWebResponse         <-response-
                 Stream <=Copy= Stream
      <-response- HttpListenerResponse

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?

回答1:

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