WebSocketResponse.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. #if !BESTHTTP_DISABLE_WEBSOCKET && (!UNITY_WEBGL || UNITY_EDITOR)
  2. using System;
  3. using System.IO;
  4. using System.Threading;
  5. using System.Collections.Generic;
  6. using System.Collections.Concurrent;
  7. using System.Text;
  8. using BestHTTP.Extensions;
  9. using BestHTTP.WebSocket.Frames;
  10. using BestHTTP.Core;
  11. using BestHTTP.PlatformSupport.Memory;
  12. using BestHTTP.Logger;
  13. namespace BestHTTP.WebSocket
  14. {
  15. public sealed class WebSocketResponse : HTTPResponse, IHeartbeat, IProtocol
  16. {
  17. /// <summary>
  18. /// Capacity of the RTT buffer where the latencies are kept.
  19. /// </summary>
  20. public static int RTTBufferCapacity = 5;
  21. #region Public Interface
  22. /// <summary>
  23. /// A reference to the original WebSocket instance. Used for accessing extensions.
  24. /// </summary>
  25. public WebSocket WebSocket { get; internal set; }
  26. /// <summary>
  27. /// Called when a Text message received
  28. /// </summary>
  29. public Action<WebSocketResponse, string> OnText;
  30. /// <summary>
  31. /// Called when a Binary message received
  32. /// </summary>
  33. public Action<WebSocketResponse, byte[]> OnBinary;
  34. /// <summary>
  35. /// Called when an incomplete frame received. No attempt will be made to reassemble these fragments.
  36. /// </summary>
  37. public Action<WebSocketResponse, WebSocketFrameReader> OnIncompleteFrame;
  38. /// <summary>
  39. /// Called when the connection closed.
  40. /// </summary>
  41. public Action<WebSocketResponse, UInt16, string> OnClosed;
  42. /// <summary>
  43. /// IProtocol's ConnectionKey property.
  44. /// </summary>
  45. public HostConnectionKey ConnectionKey { get; private set; }
  46. /// <summary>
  47. /// Indicates whether the connection to the server is closed or not.
  48. /// </summary>
  49. public bool IsClosed { get { return closed; } }
  50. /// <summary>
  51. /// IProtocol.LoggingContext implementation.
  52. /// </summary>
  53. LoggingContext IProtocol.LoggingContext { get => this.Context; }
  54. /// <summary>
  55. /// On what frequency we have to send a ping to the server.
  56. /// </summary>
  57. public TimeSpan PingFrequnecy { get; private set; }
  58. /// <summary>
  59. /// Maximum size of a fragment's payload data. Its default value is WebSocket.MaxFragmentSize's value.
  60. /// </summary>
  61. public uint MaxFragmentSize { get; set; }
  62. /// <summary>
  63. /// Length of unsent, buffered up data in bytes.
  64. /// </summary>
  65. public int BufferedAmount { get { return this._bufferedAmount; } }
  66. private int _bufferedAmount;
  67. /// <summary>
  68. /// Calculated latency from the Round-Trip Times we store in the rtts field.
  69. /// </summary>
  70. public int Latency { get; private set; }
  71. /// <summary>
  72. /// When we received the last frame.
  73. /// </summary>
  74. public DateTime lastMessage = DateTime.MinValue;
  75. #endregion
  76. #region Private Fields
  77. private List<WebSocketFrameReader> IncompleteFrames = new List<WebSocketFrameReader>();
  78. private ConcurrentQueue<WebSocketFrameReader> CompletedFrames = new ConcurrentQueue<WebSocketFrameReader>();
  79. private WebSocketFrameReader CloseFrame;
  80. private ConcurrentQueue<WebSocketFrame> unsentFrames = new ConcurrentQueue<WebSocketFrame>();
  81. private volatile AutoResetEvent newFrameSignal = new AutoResetEvent(false);
  82. private int sendThreadCreated = 0;
  83. private int closedThreads = 0;
  84. /// <summary>
  85. /// True if we sent out a Close message to the server
  86. /// </summary>
  87. private volatile bool closeSent;
  88. /// <summary>
  89. /// True if this WebSocket connection is closed
  90. /// </summary>
  91. private volatile bool closed;
  92. /// <summary>
  93. /// When we sent out the last ping.
  94. /// </summary>
  95. private DateTime lastPing = DateTime.MinValue;
  96. private bool waitingForPong = false;
  97. /// <summary>
  98. /// A circular buffer to store the last N rtt times calculated by the pong messages.
  99. /// </summary>
  100. private CircularBuffer<int> rtts = new CircularBuffer<int>(WebSocketResponse.RTTBufferCapacity);
  101. #endregion
  102. internal WebSocketResponse(HTTPRequest request, Stream stream, bool isStreamed, bool isFromCache)
  103. : base(request, stream, isStreamed, isFromCache)
  104. {
  105. base.IsClosedManually = true;
  106. this.ConnectionKey = new HostConnectionKey(this.baseRequest.CurrentUri.Host, HostDefinition.GetKeyForRequest(this.baseRequest));
  107. closed = false;
  108. MaxFragmentSize = WebSocket.MaxFragmentSize;
  109. }
  110. internal void StartReceive()
  111. {
  112. if (IsUpgraded)
  113. BestHTTP.PlatformSupport.Threading.ThreadedRunner.RunLongLiving(ReceiveThreadFunc);
  114. }
  115. internal void CloseStream()
  116. {
  117. if (base.Stream != null)
  118. {
  119. try
  120. {
  121. base.Stream.Dispose();
  122. }
  123. catch
  124. { }
  125. }
  126. }
  127. #region Public interface for interacting with the server
  128. /// <summary>
  129. /// It will send the given message to the server in one frame.
  130. /// </summary>
  131. public void Send(string message)
  132. {
  133. if (message == null)
  134. throw new ArgumentNullException("message must not be null!");
  135. int count = System.Text.Encoding.UTF8.GetByteCount(message);
  136. byte[] data = BufferPool.Get(count, true);
  137. System.Text.Encoding.UTF8.GetBytes(message, 0, message.Length, data, 0);
  138. var frame = new WebSocketFrame(this.WebSocket, WebSocketFrameTypes.Text, data, 0, (ulong)count, true, true);
  139. if (frame.Data != null && frame.Data.Length > this.MaxFragmentSize)
  140. {
  141. WebSocketFrame[] additionalFrames = frame.Fragment(this.MaxFragmentSize);
  142. Send(frame);
  143. if (additionalFrames != null)
  144. for (int i = 0; i < additionalFrames.Length; ++i)
  145. Send(additionalFrames[i]);
  146. }
  147. else
  148. Send(frame);
  149. BufferPool.Release(data);
  150. }
  151. /// <summary>
  152. /// It will send the given data to the server in one frame.
  153. /// </summary>
  154. public void Send(byte[] data)
  155. {
  156. if (data == null)
  157. throw new ArgumentNullException("data must not be null!");
  158. WebSocketFrame frame = new WebSocketFrame(this.WebSocket, WebSocketFrameTypes.Binary, data);
  159. if (frame.Data != null && frame.Data.Length > this.MaxFragmentSize)
  160. {
  161. WebSocketFrame[] additionalFrames = frame.Fragment(this.MaxFragmentSize);
  162. Send(frame);
  163. if (additionalFrames != null)
  164. for (int i = 0; i < additionalFrames.Length; ++i)
  165. Send(additionalFrames[i]);
  166. }
  167. else
  168. Send(frame);
  169. }
  170. /// <summary>
  171. /// Will send count bytes from a byte array, starting from offset.
  172. /// </summary>
  173. public void Send(byte[] data, ulong offset, ulong count)
  174. {
  175. if (data == null)
  176. throw new ArgumentNullException("data must not be null!");
  177. if (offset + count > (ulong)data.Length)
  178. throw new ArgumentOutOfRangeException("offset + count >= data.Length");
  179. WebSocketFrame frame = new WebSocketFrame(this.WebSocket, WebSocketFrameTypes.Binary, data, offset, count, true, true);
  180. if (frame.Data != null && frame.Data.Length > this.MaxFragmentSize)
  181. {
  182. WebSocketFrame[] additionalFrames = frame.Fragment(this.MaxFragmentSize);
  183. Send(frame);
  184. if (additionalFrames != null)
  185. for (int i = 0; i < additionalFrames.Length; ++i)
  186. Send(additionalFrames[i]);
  187. }
  188. else
  189. Send(frame);
  190. }
  191. /// <summary>
  192. /// It will send the given frame to the server.
  193. /// </summary>
  194. public void Send(WebSocketFrame frame)
  195. {
  196. if (frame == null)
  197. throw new ArgumentNullException("frame is null!");
  198. if (closed || closeSent)
  199. return;
  200. this.unsentFrames.Enqueue(frame);
  201. if (Interlocked.CompareExchange(ref this.sendThreadCreated, 1, 0) == 0)
  202. {
  203. HTTPManager.Logger.Information("WebSocketResponse", "Send - Creating thread", this.Context);
  204. BestHTTP.PlatformSupport.Threading.ThreadedRunner.RunLongLiving(SendThreadFunc);
  205. }
  206. Interlocked.Add(ref this._bufferedAmount, frame.Data != null ? frame.DataLength : 0);
  207. //if (HTTPManager.Logger.Level <= Logger.Loglevels.All)
  208. // HTTPManager.Logger.Information("WebSocketResponse", "Signaling SendThread!", this.Context);
  209. newFrameSignal.Set();
  210. }
  211. /// <summary>
  212. /// It will initiate the closing of the connection to the server.
  213. /// </summary>
  214. public void Close()
  215. {
  216. Close(1000, "Bye!");
  217. }
  218. /// <summary>
  219. /// It will initiate the closing of the connection to the server.
  220. /// </summary>
  221. public void Close(UInt16 code, string msg)
  222. {
  223. if (closed)
  224. return;
  225. HTTPManager.Logger.Verbose("WebSocketResponse", string.Format("Close({0}, \"{1}\")", code, msg), this.Context);
  226. WebSocketFrame frame;
  227. while (this.unsentFrames.TryDequeue(out frame))
  228. ;
  229. //this.unsentFrames.Clear();
  230. Interlocked.Exchange(ref this._bufferedAmount, 0);
  231. Send(new WebSocketFrame(this.WebSocket, WebSocketFrameTypes.ConnectionClose, WebSocket.EncodeCloseData(code, msg)));
  232. }
  233. public void StartPinging(int frequency)
  234. {
  235. if (frequency < 100)
  236. throw new ArgumentException("frequency must be at least 100 milliseconds!");
  237. PingFrequnecy = TimeSpan.FromMilliseconds(frequency);
  238. lastMessage = DateTime.UtcNow;
  239. SendPing();
  240. HTTPManager.Heartbeats.Subscribe(this);
  241. HTTPUpdateDelegator.OnApplicationForegroundStateChanged += OnApplicationForegroundStateChanged;
  242. }
  243. #endregion
  244. #region Private Threading Functions
  245. private void SendThreadFunc()
  246. {
  247. try
  248. {
  249. using (WriteOnlyBufferedStream bufferedStream = new WriteOnlyBufferedStream(this.Stream, 16 * 1024))
  250. {
  251. while (!closed && !closeSent)
  252. {
  253. //if (HTTPManager.Logger.Level <= Logger.Loglevels.All)
  254. // HTTPManager.Logger.Information("WebSocketResponse", "SendThread - Waiting...", this.Context);
  255. newFrameSignal.WaitOne();
  256. try
  257. {
  258. //if (HTTPManager.Logger.Level <= Logger.Loglevels.All)
  259. // HTTPManager.Logger.Information("WebSocketResponse", "SendThread - Wait is over, about " + this.unsentFrames.Count.ToString() + " new frames!", this.Context);
  260. WebSocketFrame frame;
  261. while (this.unsentFrames.TryDequeue(out frame))
  262. {
  263. if (!closeSent)
  264. {
  265. using (var rawData = frame.Get())
  266. bufferedStream.Write(rawData.Data, 0, rawData.Length);
  267. BufferPool.Release(frame.Data);
  268. if (frame.Type == WebSocketFrameTypes.ConnectionClose)
  269. closeSent = true;
  270. }
  271. Interlocked.Add(ref this._bufferedAmount, -frame.DataLength);
  272. }
  273. bufferedStream.Flush();
  274. }
  275. catch (Exception ex)
  276. {
  277. if (HTTPUpdateDelegator.IsCreated)
  278. {
  279. this.baseRequest.Exception = ex;
  280. this.baseRequest.State = HTTPRequestStates.Error;
  281. }
  282. else
  283. this.baseRequest.State = HTTPRequestStates.Aborted;
  284. closed = true;
  285. }
  286. }
  287. HTTPManager.Logger.Information("WebSocketResponse", string.Format("Ending Send thread. Closed: {0}, closeSent: {1}", closed, closeSent), this.Context);
  288. }
  289. }
  290. finally
  291. {
  292. Interlocked.Exchange(ref sendThreadCreated, 0);
  293. HTTPManager.Logger.Information("WebSocketResponse", "SendThread - Closed!", this.Context);
  294. TryToCleanup();
  295. }
  296. }
  297. private void ReceiveThreadFunc()
  298. {
  299. try
  300. {
  301. while (!closed)
  302. {
  303. try
  304. {
  305. WebSocketFrameReader frame = new WebSocketFrameReader();
  306. frame.Read(this.Stream);
  307. if (HTTPManager.Logger.Level == Logger.Loglevels.All)
  308. HTTPManager.Logger.Information("WebSocketResponse", "Frame received: " + frame.Type, this.Context);
  309. lastMessage = DateTime.UtcNow;
  310. // A server MUST NOT mask any frames that it sends to the client. A client MUST close a connection if it detects a masked frame.
  311. // In this case, it MAY use the status code 1002 (protocol error)
  312. // (These rules might be relaxed in a future specification.)
  313. if (frame.HasMask)
  314. {
  315. HTTPManager.Logger.Warning("WebSocketResponse", "Protocol Error: masked frame received from server!", this.Context);
  316. Close(1002, "Protocol Error: masked frame received from server!");
  317. continue;
  318. }
  319. if (!frame.IsFinal)
  320. {
  321. if (OnIncompleteFrame == null)
  322. IncompleteFrames.Add(frame);
  323. else
  324. CompletedFrames.Enqueue(frame);
  325. continue;
  326. }
  327. switch (frame.Type)
  328. {
  329. // For a complete documentation and rules on fragmentation see http://tools.ietf.org/html/rfc6455#section-5.4
  330. // A fragmented Frame's last fragment's opcode is 0 (Continuation) and the FIN bit is set to 1.
  331. case WebSocketFrameTypes.Continuation:
  332. // Do an assemble pass only if OnFragment is not set. Otherwise put it in the CompletedFrames, we will handle it in the HandleEvent phase.
  333. if (OnIncompleteFrame == null)
  334. {
  335. frame.Assemble(IncompleteFrames);
  336. // Remove all incomplete frames
  337. IncompleteFrames.Clear();
  338. // Control frames themselves MUST NOT be fragmented. So, its a normal text or binary frame. Go, handle it as usual.
  339. goto case WebSocketFrameTypes.Binary;
  340. }
  341. else
  342. {
  343. CompletedFrames.Enqueue(frame);
  344. ProtocolEventHelper.EnqueueProtocolEvent(new ProtocolEventInfo(this));
  345. }
  346. break;
  347. case WebSocketFrameTypes.Text:
  348. case WebSocketFrameTypes.Binary:
  349. frame.DecodeWithExtensions(WebSocket);
  350. CompletedFrames.Enqueue(frame);
  351. ProtocolEventHelper.EnqueueProtocolEvent(new ProtocolEventInfo(this));
  352. break;
  353. // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in response, unless it already received a Close frame.
  354. case WebSocketFrameTypes.Ping:
  355. if (!closeSent && !closed)
  356. Send(new WebSocketFrame(this.WebSocket, WebSocketFrameTypes.Pong, frame.Data));
  357. break;
  358. case WebSocketFrameTypes.Pong:
  359. waitingForPong = false;
  360. try
  361. {
  362. // Get the ticks from the frame's payload
  363. long ticksSent = BitConverter.ToInt64(frame.Data, 0);
  364. // the difference between the current time and the time when the ping message is sent
  365. TimeSpan diff = TimeSpan.FromTicks(lastMessage.Ticks - ticksSent);
  366. // add it to the buffer
  367. this.rtts.Add((int)diff.TotalMilliseconds);
  368. // and calculate the new latency
  369. this.Latency = CalculateLatency();
  370. }
  371. catch
  372. {
  373. // https://tools.ietf.org/html/rfc6455#section-5.5
  374. // A Pong frame MAY be sent unsolicited. This serves as a
  375. // unidirectional heartbeat. A response to an unsolicited Pong frame is
  376. // not expected.
  377. }
  378. break;
  379. // If an endpoint receives a Close frame and did not previously send a Close frame, the endpoint MUST send a Close frame in response.
  380. case WebSocketFrameTypes.ConnectionClose:
  381. HTTPManager.Logger.Information("WebSocketResponse", "ConnectionClose packet received!", this.Context);
  382. CloseFrame = frame;
  383. if (!closeSent)
  384. Send(new WebSocketFrame(this.WebSocket, WebSocketFrameTypes.ConnectionClose, null));
  385. closed = true;
  386. break;
  387. }
  388. }
  389. catch (Exception e)
  390. {
  391. if (HTTPUpdateDelegator.IsCreated)
  392. {
  393. this.baseRequest.Exception = e;
  394. this.baseRequest.State = HTTPRequestStates.Error;
  395. }
  396. else
  397. this.baseRequest.State = HTTPRequestStates.Aborted;
  398. closed = true;
  399. newFrameSignal.Set();
  400. }
  401. }
  402. HTTPManager.Logger.Information("WebSocketResponse", "Ending Read thread! closed: " + closed, this.Context);
  403. }
  404. finally
  405. {
  406. HTTPManager.Heartbeats.Unsubscribe(this);
  407. HTTPUpdateDelegator.OnApplicationForegroundStateChanged -= OnApplicationForegroundStateChanged;
  408. HTTPManager.Logger.Information("WebSocketResponse", "ReceiveThread - Closed!", this.Context);
  409. TryToCleanup();
  410. }
  411. }
  412. #endregion
  413. #region Sending Out Events
  414. /// <summary>
  415. /// Internal function to send out received messages.
  416. /// </summary>
  417. void IProtocol.HandleEvents()
  418. {
  419. WebSocketFrameReader frame;
  420. while (CompletedFrames.TryDequeue(out frame))
  421. {
  422. // Bugs in the clients shouldn't interrupt the code, so we need to try-catch and ignore any exception occurring here
  423. try
  424. {
  425. switch (frame.Type)
  426. {
  427. case WebSocketFrameTypes.Continuation:
  428. HTTPManager.Logger.Verbose("WebSocketResponse", "HandleEvents - OnIncompleteFrame", this.Context);
  429. if (OnIncompleteFrame != null)
  430. OnIncompleteFrame(this, frame);
  431. break;
  432. case WebSocketFrameTypes.Text:
  433. // Any not Final frame is handled as a fragment
  434. if (!frame.IsFinal)
  435. goto case WebSocketFrameTypes.Continuation;
  436. HTTPManager.Logger.Verbose("WebSocketResponse", "HandleEvents - OnText", this.Context);
  437. if (OnText != null)
  438. OnText(this, frame.DataAsText);
  439. break;
  440. case WebSocketFrameTypes.Binary:
  441. // Any not Final frame is handled as a fragment
  442. if (!frame.IsFinal)
  443. goto case WebSocketFrameTypes.Continuation;
  444. HTTPManager.Logger.Verbose("WebSocketResponse", "HandleEvents - OnBinary", this.Context);
  445. if (OnBinary != null)
  446. OnBinary(this, frame.Data);
  447. break;
  448. }
  449. }
  450. catch (Exception ex)
  451. {
  452. HTTPManager.Logger.Exception("WebSocketResponse", "HandleEvents", ex, this.Context);
  453. }
  454. }
  455. // 2015.05.09
  456. // State checking added because if there is an error the OnClose called first, and then the OnError.
  457. // Now, when there is an error only the OnError event will be called!
  458. if (IsClosed && OnClosed != null && baseRequest.State == HTTPRequestStates.Processing)
  459. {
  460. HTTPManager.Logger.Verbose("WebSocketResponse", "HandleEvents - Calling OnClosed", this.Context);
  461. try
  462. {
  463. UInt16 statusCode = 0;
  464. string msg = string.Empty;
  465. // If we received any data, we will get the status code and the message from it
  466. if (/*CloseFrame != null && */CloseFrame.Data != null && CloseFrame.Data.Length >= 2)
  467. {
  468. if (BitConverter.IsLittleEndian)
  469. Array.Reverse(CloseFrame.Data, 0, 2);
  470. statusCode = BitConverter.ToUInt16(CloseFrame.Data, 0);
  471. if (CloseFrame.Data.Length > 2)
  472. msg = Encoding.UTF8.GetString(CloseFrame.Data, 2, CloseFrame.Data.Length - 2);
  473. CloseFrame.ReleaseData();
  474. }
  475. OnClosed(this, statusCode, msg);
  476. OnClosed = null;
  477. }
  478. catch (Exception ex)
  479. {
  480. HTTPManager.Logger.Exception("WebSocketResponse", "HandleEvents - OnClosed", ex, this.Context);
  481. }
  482. }
  483. }
  484. #endregion
  485. #region IHeartbeat Implementation
  486. void IHeartbeat.OnHeartbeatUpdate(TimeSpan dif)
  487. {
  488. DateTime now = DateTime.UtcNow;
  489. if (!waitingForPong && now - lastMessage >= PingFrequnecy)
  490. SendPing();
  491. if (waitingForPong && now - lastPing > this.WebSocket.CloseAfterNoMessage)
  492. {
  493. HTTPManager.Logger.Warning("WebSocketResponse",
  494. string.Format("No message received in the given time! Closing WebSocket. LastPing: {0}, PingFrequency: {1}, Close After: {2}, Now: {3}",
  495. this.lastPing, this.PingFrequnecy, this.WebSocket.CloseAfterNoMessage, now), this.Context);
  496. CloseWithError(HTTPRequestStates.Error, "No message received in the given time!");
  497. }
  498. }
  499. #endregion
  500. private void OnApplicationForegroundStateChanged(bool isPaused)
  501. {
  502. if (!isPaused)
  503. lastMessage = DateTime.UtcNow;
  504. }
  505. private void SendPing()
  506. {
  507. HTTPManager.Logger.Information("WebSocketResponse", "Sending Ping frame, waiting for a pong...", this.Context);
  508. lastPing = DateTime.UtcNow;
  509. waitingForPong = true;
  510. try
  511. {
  512. long ticks = DateTime.UtcNow.Ticks;
  513. var ticksBytes = BitConverter.GetBytes(ticks);
  514. var pingFrame = new WebSocketFrame(this.WebSocket, WebSocketFrameTypes.Ping, ticksBytes);
  515. Send(pingFrame);
  516. }
  517. catch
  518. {
  519. HTTPManager.Logger.Information("WebSocketResponse", "Error while sending PING message! Closing WebSocket.", this.Context);
  520. CloseWithError(HTTPRequestStates.Error, "Error while sending PING message!");
  521. }
  522. }
  523. private void CloseWithError(HTTPRequestStates state, string message)
  524. {
  525. if (!string.IsNullOrEmpty(message))
  526. this.baseRequest.Exception = new Exception(message);
  527. this.baseRequest.State = state;
  528. this.closed = true;
  529. HTTPManager.Heartbeats.Unsubscribe(this);
  530. HTTPUpdateDelegator.OnApplicationForegroundStateChanged -= OnApplicationForegroundStateChanged;
  531. CloseStream();
  532. ProtocolEventHelper.EnqueueProtocolEvent(new ProtocolEventInfo(this));
  533. }
  534. private int CalculateLatency()
  535. {
  536. if (this.rtts.Count == 0)
  537. return 0;
  538. int sumLatency = 0;
  539. for (int i = 0; i < this.rtts.Count; ++i)
  540. sumLatency += this.rtts[i];
  541. return sumLatency / this.rtts.Count;
  542. }
  543. void IProtocol.CancellationRequested()
  544. {
  545. CloseWithError(HTTPRequestStates.Aborted, null);
  546. }
  547. private void TryToCleanup()
  548. {
  549. if (Interlocked.Increment(ref this.closedThreads) == 2)
  550. {
  551. ProtocolEventHelper.EnqueueProtocolEvent(new ProtocolEventInfo(this));
  552. (newFrameSignal as IDisposable).Dispose();
  553. newFrameSignal = null;
  554. CloseStream();
  555. }
  556. }
  557. public override string ToString()
  558. {
  559. return this.ConnectionKey.ToString();
  560. }
  561. }
  562. }
  563. #endif