简体   繁体   中英

Match an asynchronous HttpWebResponse to a HttpWebRequest in C#

I'm doing some tests on the HTTP pipelining feature with C#. Everything works fine but I've got a question.

In a class, I have the following code that allows me to get a HTTPWebRequest asynchronously and handle the response :

public void getResponseAsync()
    {
        RequestState rs = new RequestState();
        rs.Request = this.webRequest;  //On ajoute la requete dans l'objet état pour pouvoir le récupérer dans la callback
        IAsyncResult ar = rs.Request.BeginGetResponse(new AsyncCallback(this.ResponseCallback), rs);      // Appel asynchrone 
    }

    public void ResponseCallback(IAsyncResult ar)
    {
        RequestState rs = (RequestState)ar.AsyncState;  //Récupération de l'objet etat 
        HttpWebRequest req = rs.Request;                //Récupération de la requete web (object HttpWebRequest)
        try //Récupération de la réponse Web    
        {
            HttpWebResponse resp = (HttpWebResponse)req.EndGetResponse(ar); 
            this.incomingBuffer = Helpers.getBufferFromStream(resp.GetResponseStream()); 
            resp.Close();
            this.state = true;
        }
        catch (Exception)
        {
            this.state = false;
        }
    }

}
// La classe RequestState est utilise pour transmettre l'objet HttpWebRequest 
// a travers l'appel asynchrone
public class RequestState
{
    public HttpWebRequest Request;

    public RequestState()
    {
        Request = null;
    }
}

That snippet works fine, but I do not understand the functionning of c#. I do not understand how C# does to identify the response packet and to associate it to my request? Because in the HTTP specifications, there is no "identificator" in the HTTP response.

So how C# does to match a response with a request? Is it with ack and seq numbers?

C# doesn't do the matching. It's handled by the operating system. Remember, those HTTP requests and responses are being transmitted and received via TCP. It's the TCP implementation that matches the low-level responses with the requests, and the asynchronous I/O layer in the operating system matches the TCP stuff with your C# callbacks.

That's a simplified explanation, but essentially correct. If you want more detail, you'll have to read up on operating system internals, specifically the implementation of Windows I/O in general and TCP in particular.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM