Why do I get to the endOfStream in a webrequest, i

2019-07-13 03:49发布

问题:

I have a webrequest that createst a persistent (keepalive) connection to the server, e.g.:

webRequest.ContentType = "application/x-www-form-urlencoded";
                    // Set the ContentLength property of the WebRequest.
                    webRequest.ContentLength = byteArray.Length;
                    webRequest.Timeout = Timeout.Infinite;
                    webRequest.KeepAlive = true;
                    webRequest.ReadWriteTimeout = Timeout.Infinite;
                    //[System.Threading.Timeout]::Infinite

                    webRequest.UserAgent = "www.socialblazeapp.com";
                    Stream dataStream = webRequest.GetRequestStream();
                    // Write the data to the request stream.
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    // Close the Stream object.
                    dataStream.Close();
                    // Get the response.
                    webResponse = (HttpWebResponse)webRequest.GetResponse();
                    Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
                    responseStream = new StreamReader(webResponse.GetResponseStream(), encode);
                    while(!responseStream.EndOfStream){ //do something}

I'm wondering why responseStream.EndOfStream becomes true after a while. I would have assumed that because this is a persistent connection, the stream would never close?

Any ideas why this is happening?

回答1:

I think you're confusing keeping the TCP connection open with keeping the response stream open. The TCP connection is the underlying transmission medium, whereas the request and response are individual entities communicated via that connection.

With a persistent connection you [in theory] could issue multiple request/response pairs across the same connection. Without a persistent connection you would essentially open the connection, issue the request, receive the response, then close the connection and then repeat that process for subsequent request/response pairs.

The response itself however is finite in size, once you're received the completed response the stream should close as there is nothing more to tell you. Once you issue another request, another response would follow; I'm not clear as to whether .Net will reuse the underlying persistent connection.



回答2:

All that is supposed to do is keep the TCP connection open. If I'm reading this correctly, that means you can reuse the same physical TCP connection for multiple requests to a given server. What it won't do is keep your stream open so that the server can send additional information.

If you really want streaming data you should either use a different protocol or straight TCP.