WebSocketResponse.cs 28 KB

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