Mustafa Ekici
Mustafa Ekici

Reputation: 7470

HttpWebResponse Async The underlying connection was closed : An unexpected error occured on a send

I m using HttpWebRequest class asynchronously as code below (its just windows application)

    private void StartWebRequest(string url)
    {

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.BeginGetResponse(new AsyncCallback(FinishWebRequest), request);


    }

    private void FinishWebRequest(IAsyncResult result)
    {
            HttpWebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse;
            Stream responseStream = response.GetResponseStream();
            int num = 100000;
            byte[] buffer = new byte[num];
            int offset = 0;
            while ((num2 = responseStream.Read(buffer, offset, 1000)) != 0)
            {
                offset += num2;
            }
            MemoryStream stream = new MemoryStream(buffer, 0, offset);
            Bitmap bitmap = (Bitmap)Image.FromStream(stream);
            bitmap.Save(@"z:\new.jpg");
            response.Close();

            responseStream.Close();
            stream.Close();

    }

sometimes i get that error:
The underlying connection was closed : An unexpected error occured on a send
Is there anyway to solve this issue?
Thanks

Upvotes: 0

Views: 1183

Answers (1)

Jeremy McGee
Jeremy McGee

Reputation: 25200

You're reading data in chunks from a remote server, but at some point the outgoing request to the remote server is failing.

As to why, check to see if there's an inner exception. It may be that you'll need to use something like e.g. Fiddler or another proxy to establish why the remote server is closing your connection.

Incidentally, is there some reason why you're reading in 1000 byte blocks? It strikes me that you may be better off just streaming directly from the server into the 100kb array you've specified. And, also, make sure that that buffer is large enough for your image...

Upvotes: 2

Related Questions