Skip to content

Commit 471e104

Browse files
committed
WIP
1 parent 1ef025b commit 471e104

File tree

1 file changed

+165
-150
lines changed

1 file changed

+165
-150
lines changed
Lines changed: 165 additions & 150 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
 /**
2-
* File name: Begingetresponse.cs
3-
* This program shows how to use BeginGetResponse and EndGetResponse methods of the
4-
* HttpWebRequest class. It also shows how to create a customized timeout.
5-
* This is important in case od asynchronous request, because the NCL classes do
6-
* not provide any off-the-shelf asynchronous timeout.
7-
* It uses an asynchronous approach to get the response for the HTTP Web Request.
8-
* The RequestState class is defined to chekc the state of the request.
9-
* After a HttpWebRequest object is created, its BeginGetResponse method is used to start
10-
* the asynchronous response phase.
11-
* Finally, the EndGetResponse method is used to end the asynchronous response phase .*/
1+
/**
2+
* File name: Begingetresponse.cs
3+
* This program shows how to use BeginGetResponse and EndGetResponse methods of the
4+
* HttpWebRequest class. It also shows how to create a customized timeout.
5+
* This is important in case od asynchronous request, because the NCL classes do
6+
* not provide any off-the-shelf asynchronous timeout.
7+
* It uses an asynchronous approach to get the response for the HTTP Web Request.
8+
* The RequestState class is defined to chekc the state of the request.
9+
* After a HttpWebRequest object is created, its BeginGetResponse method is used to start
10+
* the asynchronous response phase.
11+
* Finally, the EndGetResponse method is used to end the asynchronous response phase .*/
1212
// <Snippet1>
1313
using System;
1414
using System.Net;
@@ -18,159 +18,174 @@
1818

1919
public class RequestState
2020
{
21-
// This class stores the State of the request.
22-
const int BUFFER_SIZE = 1024;
23-
public StringBuilder requestData;
24-
public byte[] BufferRead;
25-
public HttpWebRequest request;
26-
public HttpWebResponse response;
27-
public Stream streamResponse;
28-
public RequestState()
29-
{
30-
BufferRead = new byte[BUFFER_SIZE];
31-
requestData = new StringBuilder("");
32-
request = null;
33-
streamResponse = null;
34-
}
21+
// This class stores the State of the request.
22+
const int BUFFER_SIZE = 1024;
23+
public StringBuilder ResponseBuilder;
24+
public byte[] ReadBuffer;
25+
public HttpWebRequest Request;
26+
public HttpWebResponse Response;
27+
public Stream ResponseStream;
28+
public RequestState()
29+
{
30+
ReadBuffer = new byte[BUFFER_SIZE];
31+
ResponseBuilder = new StringBuilder();
32+
Request = null;
33+
ResponseStream = null;
34+
}
35+
public void OnResponseBytesRead(int read) => ResponseBuilder.Append(Encoding.UTF8.GetString(ReadBuffer, 0, read));
3536
}
3637

3738
class HttpWebRequest_BeginGetResponse
3839
{
39-
public static ManualResetEvent allDone= new ManualResetEvent(false);
40-
const int BUFFER_SIZE = 1024;
41-
const int DefaultTimeout = 2 * 60 * 1000; // 2 minutes timeout
42-
43-
// Abort the request if the timer fires.
44-
private static void TimeoutCallback(object state, bool timedOut) {
45-
if (timedOut) {
46-
HttpWebRequest request = state as HttpWebRequest;
47-
if (request != null) {
48-
request.Abort();
49-
}
50-
}
51-
}
52-
53-
static void Main()
54-
{
55-
56-
try
57-
{
58-
// Create a HttpWebrequest object to the desired URL.
59-
HttpWebRequest myHttpWebRequest= (HttpWebRequest)WebRequest.Create("http://www.contoso.com");
60-
61-
/**
62-
* If you are behind a firewall and you do not have your browser proxy setup
63-
* you need to use the following proxy creation code.
64-
65-
// Create a proxy object.
66-
WebProxy myProxy = new WebProxy();
67-
68-
// Associate a new Uri object to the _wProxy object, using the proxy address
69-
// selected by the user.
70-
myProxy.Address = new Uri("http://myproxy");
71-
72-
73-
// Finally, initialize the Web request object proxy property with the _wProxy
74-
// object.
75-
myHttpWebRequest.Proxy=myProxy;
76-
***/
77-
// Create an instance of the RequestState and assign the previous myHttpWebRequest
78-
// object to its request field.
79-
RequestState myRequestState = new RequestState();
80-
myRequestState.request = myHttpWebRequest;
81-
82-
// Start the asynchronous request.
83-
IAsyncResult result=
84-
(IAsyncResult) myHttpWebRequest.BeginGetResponse(new AsyncCallback(RespCallback),myRequestState);
85-
86-
// this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
87-
ThreadPool.RegisterWaitForSingleObject (result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), myHttpWebRequest, DefaultTimeout, true);
88-
89-
// The response came in the allowed time. The work processing will happen in the
90-
// callback function.
91-
allDone.WaitOne();
40+
public static ManualResetEvent allDone = new ManualResetEvent(false);
41+
const int BUFFER_SIZE = 1;
42+
const int DefaultTimeout = 2 * 60 * 1000; // 2 minutes timeout
9243

93-
// Release the HttpWebResponse resource.
94-
myRequestState.response.Close();
95-
}
96-
catch(WebException e)
97-
{
98-
Console.WriteLine("\nMain Exception raised!");
99-
Console.WriteLine("\nMessage:{0}",e.Message);
100-
Console.WriteLine("\nStatus:{0}",e.Status);
101-
Console.WriteLine("Press any key to continue..........");
102-
}
103-
catch(Exception e)
44+
// Abort the request if the timer fires.
45+
private static void TimeoutCallback(object state, bool timedOut)
10446
{
105-
Console.WriteLine("\nMain Exception raised!");
106-
Console.WriteLine("Source :{0} " , e.Source);
107-
Console.WriteLine("Message :{0} " , e.Message);
108-
Console.WriteLine("Press any key to continue..........");
109-
Console.Read();
47+
if (timedOut)
48+
{
49+
HttpWebRequest request = state as HttpWebRequest;
50+
if (request != null)
51+
{
52+
request.Abort();
53+
}
54+
}
11055
}
111-
}
112-
private static void RespCallback(IAsyncResult asynchronousResult)
113-
{
114-
try
56+
57+
static void Main()
11558
{
116-
// State of request is asynchronous.
117-
RequestState myRequestState=(RequestState) asynchronousResult.AsyncState;
118-
HttpWebRequest myHttpWebRequest=myRequestState.request;
119-
myRequestState.response = (HttpWebResponse) myHttpWebRequest.EndGetResponse(asynchronousResult);
120-
121-
// Read the response into a Stream object.
122-
Stream responseStream = myRequestState.response.GetResponseStream();
123-
myRequestState.streamResponse=responseStream;
124-
125-
// Begin the Reading of the contents of the HTML page and print it to the console.
126-
IAsyncResult asynchronousInputRead = responseStream.BeginRead(myRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
127-
return;
59+
60+
try
61+
{
62+
// Create a HttpWebrequest object to the desired URL.
63+
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.contoso.com");
64+
65+
// Create an instance of the RequestState and assign the previous myHttpWebRequest
66+
// object to its request field.
67+
RequestState myRequestState = new RequestState();
68+
myRequestState.Request = httpWebRequest;
69+
70+
// Start the asynchronous request.
71+
IAsyncResult result = httpWebRequest.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState);
72+
73+
// this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
74+
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), httpWebRequest, DefaultTimeout, true);
75+
76+
// The response came in the allowed time. The work processing will happen in the
77+
// callback function.
78+
allDone.WaitOne();
79+
80+
// Release the HttpWebResponse resource.
81+
myRequestState.Response.Close();
82+
}
83+
catch (WebException e)
84+
{
85+
Console.WriteLine("\nMain(): WebException raised!");
86+
Console.WriteLine("\nMessage:{0}", e.Message);
87+
Console.WriteLine("\nStatus:{0}", e.Status);
88+
Console.WriteLine("Press any key to continue..........");
89+
Console.Read();
90+
}
91+
catch (Exception e)
92+
{
93+
Console.WriteLine("\nMain Exception raised!");
94+
Console.WriteLine("Source :{0} ", e.Source);
95+
Console.WriteLine("Message :{0} ", e.Message);
96+
Console.WriteLine("Press any key to continue..........");
97+
Console.Read();
98+
}
12899
}
129-
catch(WebException e)
100+
private static void RespCallback(IAsyncResult asynchronousResult)
130101
{
131-
Console.WriteLine("\nRespCallback Exception raised!");
132-
Console.WriteLine("\nMessage:{0}",e.Message);
133-
Console.WriteLine("\nStatus:{0}",e.Status);
102+
try
103+
{
104+
// State of request is asynchronous.
105+
RequestState requestState = (RequestState)asynchronousResult.AsyncState;
106+
HttpWebRequest request = requestState.Request;
107+
requestState.Response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
108+
109+
// Read the response into a Stream object.
110+
Stream responseStream = requestState.Response.GetResponseStream();
111+
requestState.ResponseStream = responseStream;
112+
113+
// Begin the Reading of the contents of the HTML page and print it to the console.
114+
IAsyncResult asynchronousReadResult = responseStream.BeginRead(requestState.ReadBuffer, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), requestState);
115+
while (asynchronousReadResult.CompletedSynchronously)
116+
{
117+
int read = responseStream.EndRead(asynchronousReadResult);
118+
// Read the HTML page and then print it to the console.
119+
if (read > 0)
120+
{
121+
requestState.OnResponseBytesRead(read);
122+
asynchronousReadResult = responseStream.BeginRead(requestState.ReadBuffer, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), requestState);
123+
}
124+
else
125+
{
126+
OnReadComplete(requestState);
127+
}
128+
}
129+
130+
return;
131+
}
132+
catch (WebException e)
133+
{
134+
Console.WriteLine("\nRespCallback Exception raised!");
135+
Console.WriteLine("\nMessage:{0}", e.Message);
136+
Console.WriteLine("\nStatus:{0}", e.Status);
137+
}
138+
allDone.Set();
134139
}
135-
allDone.Set();
136-
}
137-
private static void ReadCallBack(IAsyncResult asyncResult)
138-
{
139-
try
140-
{
141140

142-
RequestState myRequestState = (RequestState)asyncResult.AsyncState;
143-
Stream responseStream = myRequestState.streamResponse;
144-
int read = responseStream.EndRead( asyncResult );
145-
// Read the HTML page and then print it to the console.
146-
if (read > 0)
147-
{
148-
myRequestState.requestData.Append(Encoding.ASCII.GetString(myRequestState.BufferRead, 0, read));
149-
IAsyncResult asynchronousResult = responseStream.BeginRead( myRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
150-
return;
151-
}
152-
else
141+
private static void OnReadComplete(RequestState requestState)
153142
{
154-
Console.WriteLine("\nThe contents of the Html page are : ");
155-
if(myRequestState.requestData.Length>1)
156-
{
157-
string stringContent;
158-
stringContent = myRequestState.requestData.ToString();
159-
Console.WriteLine(stringContent);
160-
}
161-
Console.WriteLine("Press any key to continue..........");
162-
Console.ReadLine();
163-
164-
responseStream.Close();
143+
Console.WriteLine("\nThe contents of the Html page are : ");
144+
if (requestState.ResponseBuilder.Length > 1)
145+
{
146+
string stringContent;
147+
stringContent = requestState.ResponseBuilder.ToString();
148+
Console.WriteLine(stringContent);
149+
}
150+
Console.WriteLine("Press any key to continue..........");
151+
Console.ReadLine();
152+
153+
requestState.ResponseStream.Close();
165154
}
166-
}
167-
catch(WebException e)
155+
156+
private static void ReadCallBack(IAsyncResult asyncResult)
168157
{
169-
Console.WriteLine("\nReadCallBack Exception raised!");
170-
Console.WriteLine("\nMessage:{0}",e.Message);
171-
Console.WriteLine("\nStatus:{0}",e.Status);
158+
if (asyncResult.CompletedSynchronously)
159+
{
160+
// To avoid recursive synchronous calls into ReadCallBack,
161+
// synchronous completion is handled at the BeginRead call-site.
162+
return;
163+
}
164+
165+
try
166+
{
167+
RequestState requestState = (RequestState)asyncResult.AsyncState;
168+
Stream responseStream = requestState.ResponseStream;
169+
int read = responseStream.EndRead(asyncResult);
170+
// Read the HTML page and then print it to the console.
171+
if (read > 0)
172+
{
173+
requestState.OnResponseBytesRead(read);
174+
IAsyncResult asynchronousResult = responseStream.BeginRead(requestState.ReadBuffer, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), requestState);
175+
return;
176+
}
177+
else
178+
{
179+
OnReadComplete(requestState);
180+
}
181+
}
182+
catch (WebException e)
183+
{
184+
Console.WriteLine("\nReadCallBack Exception raised!");
185+
Console.WriteLine("\nMessage:{0}", e.Message);
186+
Console.WriteLine("\nStatus:{0}", e.Status);
187+
}
188+
allDone.Set();
172189
}
173-
allDone.Set();
174-
}
175-
// </Snippet1>
190+
// </Snippet1>
176191
}

0 commit comments

Comments
 (0)