Expand my Community achievements bar.

.NET Server Integration http_post

Avatar

Level 1

Hi,

I noticed that the server utility class communicates with the LCCS with post and get using

HttpWebRequest. Could the http_post be recoded so the HttpWebRequests are done asynchronously

instead of synchronously. With large number of requests performing these actions synchronously

will cause issues.

Thanks,

Bartosz.

Here is an example implemention of http_post_anync:


        public static ManualResetEvent allDone = new ManualResetEvent(false);
        const int BUFFER_SIZE = 1024;

        public static void http_post_async(string url, string data, NameValueCollection headers)
        {
            if (Utils.DEBUG)
            {
                Console.WriteLine("http_post: " + url + " " + data);
                if (headers != null)
                    for (int i = 0; i < headers.Count; i++)
                        Console.WriteLine("  {0}: {1}", headers.GetKey(i), headers.Get(i));
            }

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.AllowAutoRedirect = false;
            request.Method = "POST";

            if (headers != null)
            {
                if (headers["Content-Type"] != null)
                {
                    request.ContentType = headers["Content-Type"];
                    headers.Remove("Content-Type");
                }
                else
                    request.ContentType = "application/x-www-form-urlencoded";

                if (headers.Count > 0)
                    request.Headers.Add(headers);
            }

            Encoding encoding = new UTF8Encoding();
            byte[] dataBytes = encoding.GetBytes(data);

            request.ContentLength = dataBytes.Length;

            Stream requestStream = request.GetRequestStream();
            requestStream.Write(dataBytes, 0, dataBytes.Length);
            requestStream.Close();

            // Async request start
            RequestState rs = new RequestState();

            // Put the request into the state object so it can be passed around.
            rs.Request = request;


            // Issue the async request.
            IAsyncResult r = (IAsyncResult)request.BeginGetResponse(
               new AsyncCallback(RespCallback), rs);

            // Wait until the ManualResetEvent is set so that the application
            // does not exit until after the callback is called.
            allDone.WaitOne();
            // Async Request end


        }

        private static void RespCallback(IAsyncResult ar)
        {
            // Get the RequestState object from the async result.
            RequestState rs = (RequestState)ar.AsyncState;

            // Get the WebRequest from RequestState.
            HttpWebRequest req = (HttpWebRequest)rs.Request;

            // Call EndGetResponse, which produces the WebResponse object
            //  that came from the request issued above.
            HttpWebResponse response = (HttpWebResponse)req.EndGetResponse(ar);

            //  Start reading data from the response stream.
            Stream ResponseStream = response.GetResponseStream();

            // Store the response stream in RequestState to read
            // the stream asynchronously.
            rs.ResponseStream = ResponseStream;

            //  Pass rs.BufferRead to BeginRead. Read data into rs.BufferRead
            IAsyncResult iarRead = ResponseStream.BeginRead(rs.BufferRead, 0,
               BUFFER_SIZE, new AsyncCallback(ReadCallBack), rs);

        }


        private static void ReadCallBack(IAsyncResult asyncResult)
        {
            // Get the RequestState object from AsyncResult.
            RequestState rs = (RequestState)asyncResult.AsyncState;

            // Retrieve the ResponseStream that was set in RespCallback.
            Stream responseStream = rs.ResponseStream;

            // Read rs.BufferRead to verify that it contains data.
            int read = responseStream.EndRead(asyncResult);
            if (read > 0)
            {
                // Prepare a Char array buffer for converting to Unicode.
                Char[] charBuffer = new Char[BUFFER_SIZE];

                // Convert byte stream to Char array and then to String.
                // len contains the number of characters converted to Unicode.
                int len = rs.StreamDecode.GetChars(rs.BufferRead, 0, read, charBuffer, 0);

                String str = new String(charBuffer, 0, len);

                // Append the recently read data to the RequestData stringbuilder
                // object contained in RequestState.
                rs.RequestData.Append(
                   Encoding.UTF8.GetString(rs.BufferRead, 0, read));

                // Continue reading data until
                // responseStream.EndRead returns –1.
                IAsyncResult ar = responseStream.BeginRead(
                   rs.BufferRead, 0, BUFFER_SIZE,
                   new AsyncCallback(ReadCallBack), rs);
            }
            else
            {
                if (rs.RequestData.Length > 0)
                {
                    //  Display data to the console.
                    string strContent;
                    strContent = rs.RequestData.ToString();
                }
                // Close down the response stream.
                responseStream.Close();
                // Set the ManualResetEvent so the main thread can exit.
                allDone.Set();
            }
            return;
        }   

0 Replies