public void Abort() { object locker = HTTPManager.Locker; lock (locker) { HTTPConnection connectionWith = HTTPManager.GetConnectionWith(this); if (connectionWith == null) { if (!HTTPManager.RemoveFromQueue(this)) { HTTPManager.Logger.Warning("HTTPRequest", "Abort - No active connection found with this request! (The request may already finished?)"); } this.State = HTTPRequestStates.Aborted; } else { if (this.Response != null && this.Response.IsStreamed) { this.Response.Dispose(); } connectionWith.Abort(HTTPConnectionStates.AbortRequested); } } }
void OnApplicationQuit() { HTTPManager.Logger.Information("HTTPUpdateDelegator", "OnApplicationQuit Called!"); if (OnBeforeApplicationQuit != null) { try { if (!OnBeforeApplicationQuit()) { HTTPManager.Logger.Information("HTTPUpdateDelegator", "OnBeforeApplicationQuit call returned false, postponing plugin shutdown."); return; } } catch (System.Exception ex) { HTTPManager.Logger.Exception("HTTPUpdateDelegator", string.Empty, ex); } } IsThreadRunning = false; if (!IsCreated) { return; } IsCreated = false; HTTPManager.OnQuit(); }
void OnApplicationQuit() { if (OnBeforeApplicationQuit != null) { try { if (!OnBeforeApplicationQuit()) { HTTPManager.Logger.Information("HTTPUpdateDelegator", "OnBeforeApplicationQuit call returned false, postponing plugin shutdown."); return; } } catch (System.Exception ex) { HTTPManager.Logger.Exception("HTTPUpdateDelegator", string.Empty, ex); } } IsThreadRunning = false; if (!IsCreated) { return; } IsCreated = false; HTTPManager.OnQuit(); #if UNITY_EDITOR UnityEditor.EditorApplication.update -= Update; UnityEditor.EditorApplication.playmodeStateChanged -= OnPlayModeStateChanged; #endif }
void Update() { if (!IsThreaded) { HTTPManager.OnUpdate(); } }
public static Task <T> CreateTask <T>(HTTPRequest request, CancellationToken token, Action <HTTPRequest, HTTPResponse, TaskCompletionSource <T> > callback) { HTTPManager.Setup(); var tcs = new TaskCompletionSource <T>(); request.Callback = (req, resp) => { if (token.IsCancellationRequested) { tcs.SetCanceled(); } else { callback(req, resp, tcs); } }; if (token.CanBeCanceled) { token.Register((state) => (state as HTTPRequest)?.Abort(), request); } if (request.State == HTTPRequestStates.Initial) { request.Send(); } return(tcs.Task); }
private void Setup() { if (IsSetupCalled) { return; } IsSetupCalled = true; HTTPManager.Setup(); #if UNITY_WEBGL && !UNITY_EDITOR // Threads are not implemented in WEBGL builds, disable it for now. IsThreaded = false; #endif if (IsThreaded) { PlatformSupport.Threading.ThreadedRunner.RunLongLiving(ThreadFunc); } // Unity doesn't tolerate well if the DontDestroyOnLoad called when purely in editor mode. So, we will set the flag // only when we are playing, or not in the editor. if (!Application.isEditor || Application.isPlaying) { GameObject.DontDestroyOnLoad(this.gameObject); } HTTPManager.Logger.Information("HTTPUpdateDelegator", "Setup done!"); }
/// <summary> /// Aborts an already estabilished connection, so no further download or upload are done. /// </summary> public void Abort() { lock (HTTPManager.Locker) { // Get the parent connection var connection = HTTPManager.GetConnectionWith(this); // No Connection found for this request, maybe not even started if (connection == null) { // so try to remove from the request queue if (!HTTPManager.RemoveFromQueue(this)) { HTTPManager.Logger.Warning("HTTPRequest", "Abort - No active connection found with this request! (The request may already finished?)"); } this.State = HTTPRequestStates.Aborted; } else { // destroy the incomplete response if (Response != null && Response.IsStreamed) { Response.Dispose(); } // send an abort request to the connection connection.Abort(HTTPConnectionStates.AbortRequested); } } }
public bool MoveNext() { lock (HTTPManager.Locker) { HTTPConnection connection = HTTPManager.GetConnectionWith(this); return(connection != null && connection.State <= HTTPConnectionStates.WaitForRecycle); } }
private static bool CanProcessFromQueue() { for (int i = 0; i < HTTPManager.RequestQueue.Count; i++) { if (HTTPManager.FindOrCreateFreeConnection(HTTPManager.RequestQueue[i]) != null) { return(true); } } return(false); }
public bool MoveNext() { object locker = HTTPManager.Locker; bool result; lock (locker) { HTTPConnection connectionWith = HTTPManager.GetConnectionWith(this); result = (connectionWith != null && connectionWith.State <= HTTPConnectionStates.WaitForRecycle); } return(result); }
void Update() { if (!IsSetupCalled) { Setup(); } if (!IsThreaded) { HTTPManager.OnUpdate(); } }
void ThreadFunc(object obj) { IsThreadRunning = true; while (IsThreadRunning) { HTTPManager.OnUpdate(); #if NETFX_CORE await Task.Delay(ThreadFrequencyInMS); #else System.Threading.Thread.Sleep(ThreadFrequencyInMS); #endif } }
/// <summary> /// Aborts an already estabilished connection, so no further download or upload are done. /// </summary> public void Abort() { lock (HTTPManager.Locker) { // Get the parent connection var connection = HTTPManager.GetConnectionWith(this); if (connection == null) { UnityEngine.Debug.LogWarning("Abort - No active connection found with this request! (The download may already finished?)"); return; } connection.Abort(HTTPConnectionStates.AbortRequested); } }
void OnApplicationQuit() { if (!IsCreated) { return; } IsCreated = false; HTTPManager.OnQuit(); #if UNITY_EDITOR UnityEditor.EditorApplication.update -= Update; UnityEditor.EditorApplication.playmodeStateChanged -= OnPlayModeStateChanged; #endif }
internal static string GetRootCacheFolder() { try { if (HTTPManager.RootCacheFolderProvider != null) { return(HTTPManager.RootCacheFolderProvider()); } } catch (Exception ex) { HTTPManager.Logger.Exception("HTTPManager", "GetRootCacheFolder", ex); } return(Application.persistentDataPath); }
void OnPlayModeStateChanged(UnityEditor.PlayModeStateChange playMode) { if (playMode == UnityEditor.PlayModeStateChange.EnteredPlayMode) { UnityEditor.EditorApplication.update -= Update; } else if (playMode == UnityEditor.PlayModeStateChange.EnteredEditMode) { UnityEditor.EditorApplication.update -= Update; UnityEditor.EditorApplication.update += Update; HTTPUpdateDelegator.ResetSetup(); HTTPManager.ResetSetup(); } }
private static HTTPConnection FindOrCreateFreeConnection(HTTPRequest request) { HTTPConnection hTTPConnection = null; string keyForRequest = HTTPManager.GetKeyForRequest(request); List <HTTPConnection> list; if (HTTPManager.Connections.TryGetValue(keyForRequest, out list)) { int num = 0; for (int i = 0; i < list.Count; i++) { if (list[i].State < HTTPConnectionStates.Free) { num++; } } if (num <= (int)HTTPManager.MaxConnectionPerServer) { int num2 = 0; while (num2 < list.Count && hTTPConnection == null) { HTTPConnection hTTPConnection2 = list[num2]; if (hTTPConnection2 != null && hTTPConnection2.IsFree && (!hTTPConnection2.HasProxy || hTTPConnection2.LastProcessedUri == null || hTTPConnection2.LastProcessedUri.Host.Equals(request.CurrentUri.Host, StringComparison.OrdinalIgnoreCase))) { hTTPConnection = hTTPConnection2; } num2++; } } } else { HTTPManager.Connections.Add(keyForRequest, list = new List <HTTPConnection>((int)HTTPManager.MaxConnectionPerServer)); } if (hTTPConnection == null) { if (list.Count >= (int)HTTPManager.MaxConnectionPerServer) { return(null); } list.Add(hTTPConnection = new HTTPConnection(keyForRequest)); } return(hTTPConnection); }
public static HTTPRequest SendRequest(HTTPRequest request) { object locker = HTTPManager.Locker; lock (locker) { HTTPManager.Setup(); if (HTTPManager.IsCallingCallbacks) { request.State = HTTPRequestStates.Queued; HTTPManager.RequestQueue.Add(request); } else { HTTPManager.SendRequestImpl(request); } } return(request); }
void ThreadFunc(object obj) { HTTPManager.Logger.Information("HTTPUpdateDelegator", "Update Thread Started"); try { IsThreadRunning = true; while (IsThreadRunning) { HTTPManager.OnUpdate(); #if NETFX_CORE await Task.Delay(ThreadFrequencyInMS); #else System.Threading.Thread.Sleep(ThreadFrequencyInMS); #endif } } finally { HTTPManager.Logger.Information("HTTPUpdateDelegator", "Update Thread Ended"); } }
private static void SendRequestImpl(HTTPRequest request) { HTTPConnection conn = HTTPManager.FindOrCreateFreeConnection(request); if (conn != null) { if (HTTPManager.ActiveConnections.Find((HTTPConnection c) => c == conn) == null) { HTTPManager.ActiveConnections.Add(conn); } HTTPManager.FreeConnections.Remove(conn); request.State = HTTPRequestStates.Processing; request.Prepare(); conn.Process(request); } else { request.State = HTTPRequestStates.Queued; HTTPManager.RequestQueue.Add(request); } }
Connect() { Uri uri = CurrentRequest.HasProxy ? CurrentRequest.Proxy.Address : CurrentRequest.CurrentUri; if (Client == null) { Client = new TcpClient(); } if (!Client.Connected) { Client.ConnectTimeout = CurrentRequest.ConnectTimeout; //#if NETFX_CORE //await //#endif string address = HTTPManager.GetHostCache(uri.Host); if (!string.IsNullOrEmpty(address)) { Client.Connect(address, uri.Port); } else { Client.Connect(uri.Host, uri.Port); if (Client.IsConnected()) { System.Net.IPEndPoint end_point = Client.Client.RemoteEndPoint as System.Net.IPEndPoint; address = end_point.Address.ToString(); HTTPManager.AddHostCache(uri.Host, address); } } } else { // NGUIDebug.print("Client.Connected ========>" + Client.Connected); } if (Stream == null) { if (HasProxy && !Proxy.IsTransparent) { Stream = Client.GetStream(); var outStream = new BinaryWriter(Stream); outStream.Write(string.Format("CONNECT {0}:{1} HTTP/1.1", CurrentRequest.CurrentUri.Host, CurrentRequest.CurrentUri.Port).GetASCIIBytes()); outStream.Write(HTTPRequest.EOL); outStream.Write(string.Format("Host: {0}:{1}", CurrentRequest.CurrentUri.Host, CurrentRequest.CurrentUri.Port).GetASCIIBytes()); outStream.Write(HTTPRequest.EOL); outStream.Write(string.Format("Proxy-Connection: Keep-Alive")); outStream.Write(HTTPRequest.EOL); outStream.Write(HTTPRequest.EOL); outStream.Flush(); ReadTo(Stream, HTTPResponse.LF); ReadTo(Stream, HTTPResponse.LF); } if (HTTPProtocolFactory.IsSecureProtocol(uri)) { // On WP8 there are no Mono, so we must use the 'alternate' TlsHandlers #if !UNITY_WP8 && !NETFX_CORE if (CurrentRequest.UseAlternateSSL) { #endif var handler = new TlsClientProtocol(Client.GetStream(), new Org.BouncyCastle.Security.SecureRandom()); handler.Connect(new LegacyTlsClient(new AlwaysValidVerifyer())); Stream = handler.Stream; #if !UNITY_WP8 && !NETFX_CORE } else { SslStream sslStream = new SslStream(Client.GetStream(), false, (sender, cert, chain, errors) => { return(CurrentRequest.CallCustomCertificationValidator(cert, chain)); }); if (!sslStream.IsAuthenticated) { sslStream.AuthenticateAsClient(uri.Host); } Stream = sslStream; } #endif } else { Stream = Client.GetStream(); } } }
public static HTTPRequest SendRequest(string url, HTTPMethods methodType, OnRequestFinishedDelegate callback) { return(HTTPManager.SendRequest(new HTTPRequest(new Uri(url), methodType, callback))); }
public static HTTPRequest SendRequest(string url, HTTPMethods methodType, bool isKeepAlive, bool disableCache, OnRequestFinishedDelegate callback) { return(HTTPManager.SendRequest(new HTTPRequest(new Uri(url), methodType, isKeepAlive, disableCache, callback))); }
private void OnApplicationQuit() { HTTPManager.OnQuit(); }
public static void OnUpdate() { object locker = HTTPManager.Locker; lock (locker) { HTTPManager.IsCallingCallbacks = true; try { for (int i = 0; i < HTTPManager.ActiveConnections.Count; i++) { HTTPConnection hTTPConnection = HTTPManager.ActiveConnections[i]; switch (hTTPConnection.State) { case HTTPConnectionStates.Processing: hTTPConnection.HandleProgressCallback(); if (hTTPConnection.CurrentRequest.UseStreaming && hTTPConnection.CurrentRequest.Response != null && hTTPConnection.CurrentRequest.Response.HasStreamedFragments()) { hTTPConnection.HandleCallback(); } if (((!hTTPConnection.CurrentRequest.UseStreaming && hTTPConnection.CurrentRequest.UploadStream == null) || hTTPConnection.CurrentRequest.EnableTimoutForStreaming) && DateTime.UtcNow - hTTPConnection.StartTime > hTTPConnection.CurrentRequest.Timeout) { hTTPConnection.Abort(HTTPConnectionStates.TimedOut); } break; case HTTPConnectionStates.Redirected: HTTPManager.SendRequest(hTTPConnection.CurrentRequest); HTTPManager.RecycleConnection(hTTPConnection); break; case HTTPConnectionStates.Upgraded: hTTPConnection.HandleCallback(); break; case HTTPConnectionStates.WaitForProtocolShutdown: { WebSocketResponse webSocketResponse = hTTPConnection.CurrentRequest.Response as WebSocketResponse; if (webSocketResponse != null) { webSocketResponse.HandleEvents(); } if (webSocketResponse == null || webSocketResponse.IsClosed) { hTTPConnection.HandleCallback(); hTTPConnection.Dispose(); HTTPManager.RecycleConnection(hTTPConnection); } break; } case HTTPConnectionStates.WaitForRecycle: hTTPConnection.CurrentRequest.FinishStreaming(); hTTPConnection.HandleCallback(); HTTPManager.RecycleConnection(hTTPConnection); break; case HTTPConnectionStates.AbortRequested: { WebSocketResponse webSocketResponse = hTTPConnection.CurrentRequest.Response as WebSocketResponse; if (webSocketResponse != null) { webSocketResponse.HandleEvents(); if (webSocketResponse.IsClosed) { hTTPConnection.HandleCallback(); hTTPConnection.Dispose(); HTTPManager.RecycleConnection(hTTPConnection); } } break; } case HTTPConnectionStates.TimedOut: if (DateTime.UtcNow - hTTPConnection.TimedOutStart > TimeSpan.FromMilliseconds(500.0)) { HTTPManager.Logger.Information("HTTPManager", "Hard aborting connection becouse of a long waiting TimedOut state"); hTTPConnection.CurrentRequest.Response = null; hTTPConnection.CurrentRequest.State = HTTPRequestStates.TimedOut; hTTPConnection.HandleCallback(); HTTPManager.RecycleConnection(hTTPConnection); } break; case HTTPConnectionStates.Closed: hTTPConnection.CurrentRequest.FinishStreaming(); hTTPConnection.HandleCallback(); HTTPManager.RecycleConnection(hTTPConnection); break; } } } finally { HTTPManager.IsCallingCallbacks = false; } if (HTTPManager.RecycledConnections.Count > 0) { for (int j = 0; j < HTTPManager.RecycledConnections.Count; j++) { HTTPConnection hTTPConnection2 = HTTPManager.RecycledConnections[j]; if (hTTPConnection2.IsFree) { HTTPManager.ActiveConnections.Remove(hTTPConnection2); HTTPManager.FreeConnections.Add(hTTPConnection2); } } HTTPManager.RecycledConnections.Clear(); } if (HTTPManager.FreeConnections.Count > 0) { for (int k = 0; k < HTTPManager.FreeConnections.Count; k++) { HTTPConnection hTTPConnection3 = HTTPManager.FreeConnections[k]; if (hTTPConnection3.IsRemovable) { List <HTTPConnection> list = null; if (HTTPManager.Connections.TryGetValue(hTTPConnection3.ServerAddress, out list)) { list.Remove(hTTPConnection3); } hTTPConnection3.Dispose(); HTTPManager.FreeConnections.RemoveAt(k); k--; } } } if (HTTPManager.CanProcessFromQueue()) { if (HTTPManager.RequestQueue.Find((HTTPRequest req) => req.Priority != 0) != null) { HTTPManager.RequestQueue.Sort((HTTPRequest req1, HTTPRequest req2) => req1.Priority - req2.Priority); } HTTPRequest[] array = HTTPManager.RequestQueue.ToArray(); HTTPManager.RequestQueue.Clear(); for (int l = 0; l < array.Length; l++) { HTTPManager.SendRequest(array[l]); } } } if (HTTPManager.heartbeats != null) { HTTPManager.heartbeats.Update(); } }
private void LateUpdate() { HTTPManager.OnUpdate(); }
public HTTPRequest Send() { return(HTTPManager.SendRequest(this)); }
public void Send() { HTTPManager.SendRequest(this); }
void Update() { HTTPManager.OnUpdate(); }
void OnDisable() { HTTPManager.OnQuit(); }