ConnectionBase.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. using System;
  2. using System.Threading;
  3. #if NETFX_CORE
  4. using System.Threading.Tasks;
  5. //Disable CD4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.
  6. #pragma warning disable 4014
  7. //Disable warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
  8. #pragma warning disable 1998
  9. #endif
  10. namespace BestHTTP
  11. {
  12. internal delegate void HTTPConnectionRecycledDelegate(ConnectionBase conn);
  13. internal abstract class ConnectionBase : IDisposable
  14. {
  15. #region Public Properties
  16. /// <summary>
  17. /// The address of the server that this connection is bound to.
  18. /// </summary>
  19. public string ServerAddress { get; protected set; }
  20. /// <summary>
  21. /// The state of this connection.
  22. /// </summary>
  23. public HTTPConnectionStates State { get; protected set; }
  24. /// <summary>
  25. /// It's true if this connection is available to process a HTTPRequest.
  26. /// </summary>
  27. public bool IsFree { get { return State == HTTPConnectionStates.Initial || State == HTTPConnectionStates.Free; } }
  28. /// <summary>
  29. /// Returns true if it's an active connection.
  30. /// </summary>
  31. public bool IsActive { get { return State > HTTPConnectionStates.Initial && State < HTTPConnectionStates.Free; } }
  32. /// <summary>
  33. /// If the State is HTTPConnectionStates.Processing, then it holds a HTTPRequest instance. Otherwise it's null.
  34. /// </summary>
  35. public HTTPRequest CurrentRequest { get; protected set; }
  36. public virtual bool IsRemovable { get { return IsFree && (DateTime.UtcNow - LastProcessTime) > HTTPManager.MaxConnectionIdleTime; } }
  37. /// <summary>
  38. /// When we start to process the current request. It's set after the connection is established.
  39. /// </summary>
  40. public DateTime StartTime { get; protected set; }
  41. /// <summary>
  42. /// When this connection timed out.
  43. /// </summary>
  44. public DateTime TimedOutStart { get; protected set; }
  45. #if !BESTHTTP_DISABLE_PROXY
  46. public bool HasProxy { get { return this.CurrentRequest != null && this.CurrentRequest.Proxy != null; } }
  47. #endif
  48. public Uri LastProcessedUri { get; protected set; }
  49. #endregion
  50. #region Protected Fields
  51. protected DateTime LastProcessTime;
  52. protected HTTPConnectionRecycledDelegate OnConnectionRecycled = null;
  53. #endregion
  54. #region Privates
  55. private bool IsThreaded;
  56. #endregion
  57. public ConnectionBase(string serverAddress)
  58. :this(serverAddress, true)
  59. {}
  60. public ConnectionBase(string serverAddress, bool threaded)
  61. {
  62. this.ServerAddress = serverAddress;
  63. this.State = HTTPConnectionStates.Initial;
  64. this.LastProcessTime = DateTime.UtcNow;
  65. this.IsThreaded = threaded;
  66. }
  67. internal abstract void Abort(HTTPConnectionStates hTTPConnectionStates);
  68. internal void Process(HTTPRequest request)
  69. {
  70. if (State == HTTPConnectionStates.Processing)
  71. throw new Exception("Connection already processing a request!");
  72. StartTime = DateTime.MaxValue;
  73. State = HTTPConnectionStates.Processing;
  74. CurrentRequest = request;
  75. if (IsThreaded)
  76. {
  77. #if NETFX_CORE
  78. #pragma warning disable 4014
  79. Windows.System.Threading.ThreadPool.RunAsync(ThreadFunc);
  80. #pragma warning restore 4014
  81. #else
  82. ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadFunc));
  83. //new Thread(ThreadFunc)
  84. // .Start();
  85. #endif
  86. }
  87. else
  88. ThreadFunc(null);
  89. }
  90. protected virtual
  91. #if NETFX_CORE
  92. async
  93. #endif
  94. void ThreadFunc(object param)
  95. {
  96. }
  97. internal void HandleProgressCallback()
  98. {
  99. if (CurrentRequest.OnProgress != null && CurrentRequest.DownloadProgressChanged)
  100. {
  101. try
  102. {
  103. CurrentRequest.OnProgress(CurrentRequest, CurrentRequest.Downloaded, CurrentRequest.DownloadLength);
  104. }
  105. catch (Exception ex)
  106. {
  107. HTTPManager.Logger.Exception("ConnectionBase", "HandleProgressCallback - OnProgress", ex);
  108. }
  109. CurrentRequest.DownloadProgressChanged = false;
  110. }
  111. if (CurrentRequest.OnUploadProgress != null && CurrentRequest.UploadProgressChanged)
  112. {
  113. try
  114. {
  115. CurrentRequest.OnUploadProgress(CurrentRequest, CurrentRequest.Uploaded, CurrentRequest.UploadLength);
  116. }
  117. catch (Exception ex)
  118. {
  119. HTTPManager.Logger.Exception("ConnectionBase", "HandleProgressCallback - OnUploadProgress", ex);
  120. }
  121. CurrentRequest.UploadProgressChanged = false;
  122. }
  123. }
  124. internal void HandleCallback()
  125. {
  126. try
  127. {
  128. HandleProgressCallback();
  129. if (State == HTTPConnectionStates.Upgraded)
  130. {
  131. if (CurrentRequest != null && CurrentRequest.Response != null && CurrentRequest.Response.IsUpgraded)
  132. CurrentRequest.UpgradeCallback();
  133. State = HTTPConnectionStates.WaitForProtocolShutdown;
  134. }
  135. else
  136. CurrentRequest.CallCallback();
  137. }
  138. catch (Exception ex)
  139. {
  140. HTTPManager.Logger.Exception("ConnectionBase", "HandleCallback", ex);
  141. }
  142. }
  143. internal void Recycle(HTTPConnectionRecycledDelegate onConnectionRecycled)
  144. {
  145. OnConnectionRecycled = onConnectionRecycled;
  146. if (!(State > HTTPConnectionStates.Initial && State < HTTPConnectionStates.WaitForProtocolShutdown) || State == HTTPConnectionStates.Redirected)
  147. RecycleNow();
  148. }
  149. protected void RecycleNow()
  150. {
  151. if (State == HTTPConnectionStates.TimedOut ||
  152. State == HTTPConnectionStates.Closed)
  153. LastProcessTime = DateTime.MinValue;
  154. State = HTTPConnectionStates.Free;
  155. if (CurrentRequest != null)
  156. CurrentRequest.Dispose();
  157. CurrentRequest = null;
  158. if (OnConnectionRecycled != null)
  159. {
  160. OnConnectionRecycled(this);
  161. OnConnectionRecycled = null;
  162. }
  163. }
  164. #region Dispose Pattern
  165. protected bool IsDisposed { get; private set; }
  166. public void Dispose()
  167. {
  168. Dispose(true);
  169. GC.SuppressFinalize(this);
  170. }
  171. protected virtual void Dispose(bool disposing)
  172. {
  173. IsDisposed = true;
  174. }
  175. ~ConnectionBase()
  176. {
  177. Dispose(false);
  178. }
  179. #endregion
  180. }
  181. }