public void BeginProcessRequest(Site site) { string sql = ""; int iResult = 0; this.Site = site; oDataIO = new DataIO(); SqlConnection Conn = new SqlConnection(); Conn = oDataIO.GetDBConnection("ProfilesDB"); sqlCmd = new SqlCommand(); sqlCmd.Connection = Conn; site.IsDone = false; _request = WebRequest.Create(site.URL); // Enter log record sql = "insert into FSLogOutgoing(FSID,SiteID,Details,SentDate,QueryString) " + " values ('" + site.FSID.ToString() + "'," + site.SiteID.ToString() + ",0,GetDate()," + cs(site.SearchPhrase) + ")"; sqlCmd.CommandText = sql; sqlCmd.CommandType = System.Data.CommandType.Text; iResult = sqlCmd.ExecuteNonQuery(); if (sqlCmd.Connection.State == System.Data.ConnectionState.Open) sqlCmd.Connection.Close(); _request.BeginGetResponse(new AsyncCallback(EndProcessRequest), site); }
/// <summary> /// 异步请问Http /// </summary> public static void Client3() { ThreadPool.SetMaxThreads(1000, 1000); PrintMessage("Main Thread start"); // 发出一个异步Web请求 WebRequest webrequest = WebRequest.Create("http://www.cnblogs.com/"); webrequest.BeginGetResponse(ProcessWebResponse, webrequest); Console.Read(); }
private void GenerateRequest(object state) { RequestDestination dest = (RequestDestination)state; string __requestUrl; switch (dest) { case RequestDestination.Home: __requestUrl = _homeRequestUrl; Interlocked.Increment(ref requestsSentToHome); break; case RequestDestination.Search: default: __requestUrl = RequestUrl; Interlocked.Increment(ref requestsSentToSearch); break; } try { WebRequest request = WebRequest.Create(__requestUrl); Interlocked.Increment(ref requestDone); //request.Timeout = 7000; DateTime now = DateTime.Now; request.BeginGetResponse(new AsyncCallback((result) => { WebResponse response = ((WebRequest)result.AsyncState).EndGetResponse(result); Interlocked.Increment(ref requestTotal); switch (dest) { case RequestDestination.Home: Interlocked.Add(ref totalTimeHome, (long)(DateTime.Now - now).TotalMilliseconds); Interlocked.Increment(ref requestsReceivedFromHome); break; case RequestDestination.Search: Interlocked.Add(ref totalTimeSearch, (long)(DateTime.Now - now).TotalMilliseconds); Interlocked.Increment(ref requestsReceivedFromSearch); break; } response.Close(); }), request); } catch (WebException we) { if (we.Status == WebExceptionStatus.Timeout) { Interlocked.Increment(ref requestTimeout); } Interlocked.Increment(ref requestFailed); Log(string.Format("Request failed with status {0}", we.Status.ToString()), true); } }
public void Get <T>(WebRequest request, Action <HttpStatusCode, T> onComplete, Action <Uri, Exception> onError) where T : class { ApiRequestHelper.SetStandardHeaders(request, _configuration, _credentials, _oauth); request.BeginGetResponse(HandleResponseCallback <RequestContext <string, T>, string, T>, new RequestContext <string, T> { Request = request, OnComplete = (code, s, entity) => onComplete(code, entity), OnError = onError, }); }
public void SetImage(string imageName, string decode) { string imageUrl = imageName; if (imageUrl.StartsWith("//")) { imageUrl = "https:" + imageUrl; } bool isImageFromUrl = Uri.TryCreate(imageUrl, UriKind.Absolute, out Uri uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps); if (isImageFromUrl) { try { WebRequest request = WebRequest.Create(imageUrl); Action wrapperAction = () => { request.BeginGetResponse(new AsyncCallback((arg) => { var response = (HttpWebResponse)((HttpWebRequest)arg.AsyncState).EndGetResponse(arg); Stream responseStream = response.GetResponseStream(); if (decode.ToLower() == CryptUtils.EncDec.BASE64) { responseStream = Base64ToStream(responseStream, decode); } BackgroundImage = System.Drawing.Image.FromStream(responseStream); }), request); }; wrapperAction.BeginInvoke(new AsyncCallback((arg) => { var action = (Action)arg.AsyncState; action.EndInvoke(arg); }), wrapperAction); } #if DEBUG catch (Exception e) #else catch (Exception) #endif { #if DEBUG Logger.GetLogger().Error("PanelEx SetImage error while trying to load from URL - " + e.Message); #endif } finally { } } else { BackgroundImage = UICommon.LoadImage(imageName, decode); } }
private void QueryDownload(string url) { try { // Create a request for the headers only. WebRequest request = WebRequest.Create(url); request.Method = WebRequestMethods.Http.Head; // Asynchronously perform the request. request.BeginGetResponse((ar) => { try { WebResponse response = request.EndGetResponse(ar); if (response != null) { // Get the "content-disposition" header. // We currently care for the filename only. However, at this point we could // also inform the user of the size of the file by getting the value of the: // "content-length" header. string contentDisposition = response.Headers["content-disposition"]; if (!String.IsNullOrEmpty(contentDisposition)) { // Initialize. string fileName = string.Empty; // Look for the filename part. string fileNamePart = "filename="; int index = contentDisposition.IndexOf(fileNamePart, StringComparison.InvariantCultureIgnoreCase); if (index >= 0) { fileName = contentDisposition.Substring(index + fileNamePart.Length); // Cleanup any invalid surrounding characters. fileName = fileName.Trim(Path.GetInvalidFileNameChars()).Trim(new char[] { '"', ';' }); } // If we have a filename, proceed with asking the user // and performing the actual download. if (!String.IsNullOrWhiteSpace(fileName)) { Dispatcher.BeginInvoke((Action <string, string>)RequestDownload, url, fileName); } } } } catch { } }, null); } catch { } }
protected IAsyncResult BeginWebRequest() { WebRequest request = WebRequest.Create(this.UriToCall); AsyncCallback callBack = new AsyncCallback(onCompleted); AsyncStateObject.WebRequest = request; AsyncStateObject.Stopwatch = System.Diagnostics.Stopwatch.StartNew(); return(request.BeginGetResponse(callBack, AsyncStateObject)); }
private WebResponse GetResponse(WebRequest request) { var responseHandler = request.BeginGetResponse(null, null); if (WaitHandle.WaitAny(new[] { responseHandler.AsyncWaitHandle, CancellationToken.WaitHandle }) == 1) { throw new OperationCanceledException(); } var responsex = request.EndGetResponse(responseHandler); return(responsex); }
/// <summary> /// Callback used to process request stream. /// </summary> /// <param name="asynchronousResult">Server response state.</param> protected void GetRequestStreamCallback(IAsyncResult asynchronousResult) { WebRequest webRequest = (WebRequest)asynchronousResult.AsyncState; Stream postStream = webRequest.EndGetRequestStream(asynchronousResult); string postData = GetStringFromXDocument(); byte[] bytesToSend = CompressResult(postData); postStream.Write(bytesToSend, 0, bytesToSend.Length); postStream.Close(); webRequest.BeginGetResponse(new AsyncCallback(GetResponseCallback), webRequest); }
private void GetRequestStreamCallback(IAsyncResult result) { WebRequest request = (WebRequest)result.AsyncState; using (Stream stream = request.EndGetRequestStream(result)) { stream.Write(postData, 0, postData.Length); stream.Close(); } request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request); }
protected void TryWebRequest(string method, string header, Type exception) { WebRequest wr = GetWebRequest(new Uri("http://localhost")); wr.Method = method; wr.Headers [header] = "value"; TestState state = new TestState(wr, header, exception); Enqueue(() => { wr.BeginGetResponse(new AsyncCallback(TryWebRequestGetResponse), state); }); EnqueueConditional(() => state.Complete); }
public void MakeRequest(string url, Action <bool, string> callback) { WebRequest request = WebRequest.Create(url); RequestState state = new RequestState(); state.Request = request; state.Callback = callback; ((HttpWebRequest)request).UserAgent = "SuperPutty/1.4.0.5"; IAsyncResult result = (IAsyncResult)request.BeginGetResponse( new System.AsyncCallback(RespCallback), state); }
/// <summary> /// Starts fetching a file, and notifies the OnFetchedFile event /// when done. /// </summary> public void FetchFile(string URL) { WebRequest Request = WebRequest.Create(URL); Request.Method = "GET"; RequestState ReqState = new RequestState(); ReqState.Request = Request; ReqState.TransferStart = DateTime.Now; Request.BeginGetResponse(new AsyncCallback(GotInitialResponse), ReqState); ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(AcceptAllCertifications); }
void WriteToRequestStream(IAsyncResult result) { WebRequest req = (WebRequest)result.AsyncState; Stream post_data = req.EndGetRequestStream(result); byte[] request_buffer = Encoding.UTF8.GetBytes(_Message); _Message = null; post_data.Write(request_buffer, 0, request_buffer.Length); post_data.Close(); req.BeginGetResponse(ReadResponseStream, req); }
void BeginGetResponse(WebRequest request, AsyncCallback callback, object state) { IAsyncResult result = request.BeginGetResponse(callback, state); ClientEngine.MainLoop.QueueTimeout(ConnectionTimeout, delegate { if (!result.IsCompleted) { request.Abort(); } return(false); }); }
private void OnGetRequestStreamCompleted(IAsyncResult ar, WebRequest request, byte[] data) { try { using (var output = request.EndGetRequestStream(ar)) { output.Write(data, 0, data.Length); } request.BeginGetResponse(OnGetResponseCompleted, request); } catch (Exception e) { OnWebPostError(request, e); } }
public WebResponse GetResponse(WebRequest request) { ManualResetEvent evt = new ManualResetEvent(false); WebResponse response = null; request.BeginGetResponse((IAsyncResult ar) => { response = request.EndGetResponse(ar); evt.Set(); }, null); evt.WaitOne(); return(response as WebResponse); }
/// <summary> /// DELETE - asynchronous - using actions as handlers /// </summary> /// <param name="request"></param> /// <param name="onComplete"></param> /// <param name="onError"></param> public void Delete(WebRequest request, Action <HttpStatusCode> onComplete, Action <Uri, Exception> onError) { ApiRequestHelper.SetStandardHeaders(request, _configuration, _credentials, _oauth); request.Method = "DELETE"; request.BeginGetResponse(HandleResponseCallback <RequestContext <string>, string>, new RequestContext <string> { Request = request, OnComplete = (code, s, entity) => onComplete(code), OnError = onError, }); }
/// <summary> /// Initiate an asynchronous request /// </summary> public override void Start() { #if VERBOSE Log.Write(Log.Levels.Verbose, "DataRequest: starting async request for " + m_request.Source); #endif m_state = DataRequestState.InProcess; m_webRequest = WebRequest.Create(m_request.Source); m_webRequest.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.BypassCache); m_webRequest.Proxy = WebRequest.GetSystemWebProxy(); m_requestResult = m_webRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), this); }
public byte[] Download(string url, DownloadProgressHandler progressCB) { // Ensure flag set correctly. allDone.Reset(); // Get the URI from the command line. Uri httpSite = new Uri(url); // Create the request object. WebRequest req = WebRequest.Create(httpSite); try { // Use the current user in case an NTLM Proxy or similar is used. // wr.Proxy = WebProxy.GetDefaultProxy(); req.Proxy.Credentials = CredentialCache.DefaultCredentials; } catch (Exception) {} // Create the state object. DownloadInfo info = new DownloadInfo(); // Put the request into the state object so it can be passed around. info.Request = req; // Assign the callbacks info.ProgressCallback += progressCB; // Issue the async request. IAsyncResult r = (IAsyncResult)req.BeginGetResponse(new AsyncCallback(ResponseCallback), info); // Wait until the ManualResetEvent is set so that the application // does not exit until after the callback is called. allDone.WaitOne(); // Pass back the downloaded information. if (info.useFastBuffers) { return(info.dataBufferFast); } else { byte[] data = new byte[info.dataBufferSlow.Count]; for (int b = 0; b < info.dataBufferSlow.Count; b++) { data[b] = (byte)info.dataBufferSlow[b]; } return(data); } }
/// <summary> /// Loads this <see cref="AtomEntry"/> instance asynchronously using the specified <see cref="Uri"/>, <see cref="SyndicationResourceLoadSettings"/>, <see cref="ICredentials"/>, and <see cref="IWebProxy"/>. /// </summary> /// <param name="source">A <see cref="Uri"/> that represents the URL of the syndication resource XML data.</param> /// <param name="settings">The <see cref="SyndicationResourceLoadSettings"/> object used to configure the <see cref="AtomEntry"/> instance. This value can be <b>null</b>.</param> /// <param name="options">A <see cref="WebRequestOptions"/> that holds options that should be applied to web requests.</param> /// <param name="userToken">A user-defined object that is passed to the method invoked when the asynchronous operation completes.</param> /// <remarks> /// <para> /// To receive notification when the operation has completed or the operation has been canceled, add an event handler to the <see cref="AtomEntry.Loaded"/> event. /// You can cancel a <see cref="LoadAsync(Uri, SyndicationResourceLoadSettings, ICredentials, IWebProxy, Object)"/> operation by calling the <see cref="LoadAsyncCancel()"/> method. /// </para> /// <para> /// After calling <see cref="LoadAsync(Uri, SyndicationResourceLoadSettings, ICredentials, IWebProxy, Object)"/>, /// you must wait for the load operation to complete before attempting to load the syndication resource using the <see cref="AtomEntry.LoadAsync(Uri, Object)"/> method. /// </para> /// </remarks> /// <exception cref="ArgumentNullException">The <paramref name="source"/> is a null reference (Nothing in Visual Basic).</exception> /// <exception cref="FormatException">The <paramref name="source"/> data does not conform to the expected syndication content format. In this case, the feed remains empty.</exception> /// <exception cref="InvalidOperationException">This <see cref="AtomEntry"/> has a <see cref="LoadAsync(Uri, SyndicationResourceLoadSettings, ICredentials, IWebProxy, Object)"/> call in progress.</exception> public new void LoadAsync(Uri source, SyndicationResourceLoadSettings settings, WebRequestOptions options, Object userToken) { //------------------------------------------------------------ // Validate parameters //------------------------------------------------------------ Guard.ArgumentNotNull(source, "source"); //------------------------------------------------------------ // Use default settings if none specified by the caller //------------------------------------------------------------ if (settings == null) { settings = new SyndicationResourceLoadSettings(); } //------------------------------------------------------------ // Validate syndication resource state //------------------------------------------------------------ if (this.LoadOperationInProgress) { throw new InvalidOperationException(); } //------------------------------------------------------------ // Indicate that a load operation is in progress //------------------------------------------------------------ this.LoadOperationInProgress = true; //------------------------------------------------------------ // Reset the asynchronous load operation cancelled indicator //------------------------------------------------------------ this.AsyncLoadHasBeenCancelled = false; //------------------------------------------------------------ // Build HTTP web request used to retrieve the syndication resource //------------------------------------------------------------ asyncHttpWebRequest = SyndicationEncodingUtility.CreateWebRequest(source, options); asyncHttpWebRequest.Timeout = Convert.ToInt32(settings.Timeout.TotalMilliseconds, System.Globalization.NumberFormatInfo.InvariantInfo); //------------------------------------------------------------ // Get the async response to the web request //------------------------------------------------------------ object[] state = new object[6] { asyncHttpWebRequest, this, source, settings, options, userToken }; IAsyncResult result = asyncHttpWebRequest.BeginGetResponse(new AsyncCallback(AsyncLoadCallback), state); //------------------------------------------------------------ // Register the timeout callback //------------------------------------------------------------ ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(AsyncTimeoutCallback), state, settings.Timeout, true); }
private void RetornarLivrosLoginCallback(IAsyncResult resultado) { if (!erro) { webRequest = (WebRequest)WebRequest.Create(SiteAthenaLivros); webRequest.Headers["Connection"] = "Keep-Alive"; webRequest.BeginGetResponse(RetornarLivrosCarregarCallback, webRequest); } else { callbackLivros(null); } }
private void BeginRequest(WebRequest request, AsyncCallback callback, object state) { var result = request.BeginGetResponse(callback, state); ClientEngine.MainLoop.QueueTimeout(RequestTimeout, () => { if (!result.IsCompleted) { request.Abort(); } return(false); }); }
public void MakeRequest(string url, Action <bool, string> callback) { WebRequest request = WebRequest.Create(url); RequestState state = new RequestState { Request = request, Callback = callback }; ((HttpWebRequest)request).UserAgent = "SuperPuTTY/" + Assembly.GetExecutingAssembly().GetName().Version; IAsyncResult result = (IAsyncResult)request.BeginGetResponse(new AsyncCallback(RespCallback), state); }
private void SendRequest(string handler, AsyncCallback callback) { Uri uri = new Uri(new Uri(serverBaseTextBox.Text), handler); CredentialCache credentials = new CredentialCache(); credentials.Add(uri, "Basic", new NetworkCredential(userNameTextBox.Text, passwordTextBox.Text)); WebRequest request = HttpWebRequest.Create(uri); request.Credentials = credentials; request.BeginGetResponse(callback, request); }
private void OnGetPictures(object sender, ExecutedRoutedEventArgs e) { int pics = int.Parse(numPictures.Text); for (int i = 0; i < pics; i++) { WebRequest req = WebRequest.Create("http://localhost:9000/pictures/picture"); Task <WebResponse> task = Task.Factory.FromAsync <WebResponse>(req.BeginGetResponse(null, null), req.EndGetResponse); task.ContinueWith(UpdateUI, TaskScheduler.FromCurrentSynchronizationContext()); } }
private void menuUpdateV2Ray_Click(object sender, EventArgs e) { string latestUrl = "https://github.com/v2ray/v2ray-core/releases/latest"; //https的链接需设置 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; //通过latestUrl的重定向来获取v2ray的最新版本号 WebRequest req = WebRequest.Create(latestUrl); //异步加载链接使得UI线程不会卡死 req.BeginGetResponse(new AsyncCallback(DownloadV2Ray), req); }
private void InitControlAndData() { #if DEBUG Uri endpoint = new Uri("http://localhost:21106/SearchWord/GetUserOnlineItems"); #else Uri endpoint = new Uri("http://tkc.taokuaiche.com/SearchWord/GetUserOnlineItems"); #endif waitIndicator.DeferedVisibility = true; WebRequest request = WebRequest.Create(endpoint); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.BeginGetResponse(new AsyncCallback(ResponseReady), request); }
private void RequestReadySocket(IAsyncResult asyncResult) { WebRequest request = asyncResult.AsyncState as WebRequest; Stream requestStream = request.EndGetRequestStream(asyncResult); using (StreamWriter writer = new StreamWriter(requestStream)) { writer.Write(postData); writer.Flush(); } request.BeginGetResponse(new AsyncCallback(ResponseReadySocket), request); }
/*void ImageLocal(String resourceID) * { * image1.Source = ImageSource.FromStream(() => * { * Assembly assembly = GetType().GetTypeInfo().Assembly; * Stream stream = assembly.GetManifestResourceStream(resourceID); * return stream; * }); * }*/ void ImageWeb2(string urx) { //Uri uriReally = new Uri(urx); //Uri urx = uri; WebRequest request = WebRequest.Create(urx); request.BeginGetResponse((IAsyncResult arg) => { Stream stream = request.EndGetResponse(arg).GetResponseStream(); ImageSource imageSource = ImageSource.FromStream(() => stream); Device.BeginInvokeOnMainThread(() => image.Source = imageSource); }, null); }
private void BuildEntitySetResolver(IAsyncContinuation continuation) { if (string.IsNullOrEmpty(this.ServiceDocumentUri)) { IEntitySetResolver defaultEntitySetResolver = new DefaultEntitySetResolver(); this.CurrentWorkspace.EntitySetResolver = defaultEntitySetResolver; continuation.Continue(); } else { WebRequest serviceDocRequest = WebRequest.Create(this.ServiceDocumentUri); #if !SILVERLIGHT if (this.AuthenticationProvider.UseDefaultCredentials) { serviceDocRequest.UseDefaultCredentials = true; } else if (this.AuthenticationProvider.GetAuthenticationCredentials() != null) { serviceDocRequest.Credentials = this.AuthenticationProvider.GetAuthenticationCredentials(); } IDictionary <string, string> authenticationHeaders = this.AuthenticationProvider.GetAuthenticationHeaders(); if (authenticationHeaders != null) { foreach (var header in authenticationHeaders) { serviceDocRequest.Headers[header.Key] = header.Value; } } // we will set the timeout to 5 seconds to avoid waiting forever for a Service doc request to complete. serviceDocRequest.Timeout = 5000; #endif serviceDocRequest.BeginGetResponse( (asyncResult) => { try { XDocument serviceDocument = XDocument.Load(serviceDocRequest.EndGetResponse(asyncResult).GetResponseStream()); IEntitySetResolver entitySetResolver = this.ServiceDocumentParser.ParseServiceDocument(serviceDocument.Root); this.CurrentWorkspace.EntitySetResolver = entitySetResolver; continuation.Continue(); } catch (WebException errorWhileDownload) { continuation.Fail(errorWhileDownload); } }, null); } }
void DoWithResponse(WebRequest request, Action<HttpWebResponse> responseAction) { Action wrapperAction = () => { request.BeginGetResponse(new AsyncCallback((iar) => { var response = (HttpWebResponse)((HttpWebRequest)iar.AsyncState).EndGetResponse(iar); responseAction(response); }), request); }; wrapperAction.BeginInvoke(new AsyncCallback((iar) => { var action = (Action)iar.AsyncState; action.EndInvoke(iar); }), wrapperAction); }
// 在此方法中开始你的异步操作 // 执行后立即返回 // HttpApplication 对象此时可以立即返回到池中 private IAsyncResult BeginProcess(object sender, EventArgs e, AsyncCallback cb, object extraData) { _request = HttpWebRequest.Create("http://www.sina.com.cn"); return _request.BeginGetResponse(cb, extraData); }
/// <summary> /// Equivalent of webRequest.GetResponse, but using our own RequestState. /// This can or should be used along with web async instance's isResponseCompleted parameter /// inside a IEnumerator method capable of yield return for it, although it's mostly for clarity. /// Here's an usage example: /// /// WebAsync webAsync = new WebAsync(); StartCoroutine( webAsync.GetReseponse(webRequest) ); /// while (! webAsync.isResponseCompleted) yield return null; /// RequestState result = webAsync.requestState; /// /// </summary> /// <param name='webRequest'> /// A System.Net.WebRequest instanced var. /// </param> public IEnumerator GetResponse (WebRequest webRequest) { isResponseCompleted = false; requestState = new RequestState(); // Put the request into the state object so it can be passed around requestState.webRequest = webRequest; // Do the actual async call here IAsyncResult asyncResult = (IAsyncResult) webRequest.BeginGetResponse( new AsyncCallback(RespCallback), requestState); // WebRequest timeout won't work in async calls, so we need this instead ThreadPool.RegisterWaitForSingleObject( asyncResult.AsyncWaitHandle, new WaitOrTimerCallback(ScanTimeoutCallback), requestState, (TIMEOUT *1000), // obviously because this is in miliseconds true ); // Wait until the the call is completed while (!asyncResult.IsCompleted) { yield return null; } // Help debugging possibly unpredictable results if (requestState != null) { if (requestState.errorMessage != null) { // this is not an ERROR because there are at least 2 error messages that are expected: 404 and NameResolutionFailure - as can be seen on CheckForMissingURL Debug.Log("[WebAsync] Error message while getting response from request '"+ webRequest.RequestUri.ToString() +"': "+ requestState.errorMessage); } } isResponseCompleted = true; }
public void runNetLoop() { ManualResetEvent http_response_sync = new ManualResetEvent(false); HttpWebResponse resp = null; int registeredHandle = 0; try { conn = HttpWebRequest.Create(url);//todomt (HttpConnection)Connector.open(url); //System.Net.ServicePointManager.Expect100Continue = false; if (method == 0) conn.Method = "GET"; else conn.Method = "POST"; if (updateTime != null && updateTime.Trim().Length > 0) { conn.Headers["IfModifiedSince"] = updateTime; } registeredHandle = CRunTime.registerObject(conn); } catch (Exception e) { quit = true; Logger.log(e.ToString()); UIWorker.addUIEventLog("Async Net : Exception opening URL " + e); } int handle = registeredHandle; UIWorker.addUIEventValid(c_do_async_connect_cb, handle, cb_addr, context, 0, false, this); if (quit) return; while (!quit) { lock (conn) { if (!do_read) { try { Monitor.Wait(conn); } catch (SynchronizationLockException e) { } if (quit) return; if (!do_read) continue; } } try { if (Stream == null) { resp = null; Exception exp = null; try { http_response_sync.Reset(); conn.BeginGetResponse(delegate(IAsyncResult result) { try { Logger.log("downloading " + conn.RequestUri); resp = (HttpWebResponse)conn.EndGetResponse(result); http_response_sync.Set(); } catch (Exception we) { resp = null; exp = we; http_response_sync.Set(); } }, null); } catch (Exception ioe) { resp = null; exp = ioe; http_response_sync.Set(); } http_response_sync.WaitOne(); if (resp != null) { Stream = resp.GetResponseStream(); int status = (int)resp.StatusCode; long data_size = resp.ContentLength; string lastModifiedStr = resp.Headers["Last-Modified"]; //Logger.log("Java header, s is " + lastModifiedStr); /* * We need to send c a complete header string, so we fake it by creating the * res string. More header fields can be added later on besides the content length and last-modified * */ string res = "HTTP/1.1 " + status + " OK\r\nContent-Length: " + data_size + "\r\n"; if (lastModifiedStr != null) res += "Last-Modified:" + lastModifiedStr + "\r\n\r\n"; else res += "\r\n"; buffer = new byte[4096]; byte[] res_bytes = Syscalls.StringToAscii(res); res_bytes.CopyTo(buffer, 0); buffer_len = res_bytes.Length; buffer_cur_ptr = 0; } else { UIWorker.addUIEventLog("Exception in async net read: " + exp); eof = true; quit = true; ////buffer = new byte[4096]; //string res = "HTTP/1.1 404 Not Found\r\n"; ///*byte[] res_bytes*/buffer = Syscalls.StringToAscii(res); ////res_bytes.CopyTo(buffer, 0); //buffer_len = /*res_bytes.Length;*/buffer.Length; //buffer_cur_ptr = 0; //do_read = false; } } else { if (buffer_cur_ptr == buffer_len) { buffer_len = Stream.Read(buffer, 0, buffer.Length); if (buffer_len == -1) { eof = true; Stream.Dispose(); resp.Dispose(); } buffer_cur_ptr = 0; } } } catch (Exception e) { UIWorker.addUIEventLog("Exception in async net read: " + e); eof = true; quit = true; } lock (conn) { do_read = false; } // Call read CB if (is_valid) UIWorker.addUIEventValid(c_input_ready_cb, input_id, 0, 0, 0, false, this); } }