2
0

WebSocket.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.Net.WebSockets;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using WebSocketState = System.Net.WebSockets.WebSocketState;
  12. namespace SocketHttpListener
  13. {
  14. /// <summary>
  15. /// Implements the WebSocket interface.
  16. /// </summary>
  17. /// <remarks>
  18. /// The WebSocket class provides a set of methods and properties for two-way communication using
  19. /// the WebSocket protocol (<see href="http://tools.ietf.org/html/rfc6455">RFC 6455</see>).
  20. /// </remarks>
  21. public class WebSocket : IDisposable
  22. {
  23. #region Private Fields
  24. private Action _closeContext;
  25. private CompressionMethod _compression;
  26. private WebSocketContext _context;
  27. private CookieCollection _cookies;
  28. private AutoResetEvent _exitReceiving;
  29. private object _forConn;
  30. private readonly SemaphoreSlim _forEvent = new SemaphoreSlim(1, 1);
  31. private object _forMessageEventQueue;
  32. private readonly SemaphoreSlim _forSend = new SemaphoreSlim(1, 1);
  33. private const string _guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  34. private Queue<MessageEventArgs> _messageEventQueue;
  35. private string _protocol;
  36. private volatile WebSocketState _readyState;
  37. private AutoResetEvent _receivePong;
  38. private bool _secure;
  39. private Stream _stream;
  40. private const string _version = "13";
  41. #endregion
  42. #region Internal Fields
  43. internal const int FragmentLength = 1016; // Max value is int.MaxValue - 14.
  44. #endregion
  45. #region Internal Constructors
  46. // As server
  47. internal WebSocket(string protocol)
  48. {
  49. _protocol = protocol;
  50. }
  51. public void SetContext(HttpListenerWebSocketContext context, Action closeContextFn, Stream stream)
  52. {
  53. _context = context;
  54. _closeContext = closeContextFn;
  55. _secure = context.IsSecureConnection;
  56. _stream = stream;
  57. init();
  58. }
  59. // In the .NET Framework, this pulls the value from a P/Invoke. Here we just hardcode it to a reasonable default.
  60. public static TimeSpan DefaultKeepAliveInterval => TimeSpan.FromSeconds(30);
  61. #endregion
  62. /// <summary>
  63. /// Gets the state of the WebSocket connection.
  64. /// </summary>
  65. /// <value>
  66. /// One of the <see cref="WebSocketState"/> enum values, indicates the state of the WebSocket
  67. /// connection. The default value is <see cref="WebSocketState.Connecting"/>.
  68. /// </value>
  69. public WebSocketState ReadyState => _readyState;
  70. #region Public Events
  71. /// <summary>
  72. /// Occurs when the WebSocket connection has been closed.
  73. /// </summary>
  74. public event EventHandler<CloseEventArgs> OnClose;
  75. /// <summary>
  76. /// Occurs when the <see cref="WebSocket"/> gets an error.
  77. /// </summary>
  78. public event EventHandler<ErrorEventArgs> OnError;
  79. /// <summary>
  80. /// Occurs when the <see cref="WebSocket"/> receives a message.
  81. /// </summary>
  82. public event EventHandler<MessageEventArgs> OnMessage;
  83. /// <summary>
  84. /// Occurs when the WebSocket connection has been established.
  85. /// </summary>
  86. public event EventHandler OnOpen;
  87. #endregion
  88. #region Private Methods
  89. private async Task CloseAsync(CloseStatusCode code, string reason, bool wait)
  90. {
  91. await CloseAsync(new PayloadData(
  92. await ((ushort)code).AppendAsync(reason).ConfigureAwait(false)),
  93. !code.IsReserved(),
  94. wait).ConfigureAwait(false);
  95. }
  96. private async Task CloseAsync(PayloadData payload, bool send, bool wait)
  97. {
  98. lock (_forConn)
  99. {
  100. if (_readyState == WebSocketState.CloseSent || _readyState == WebSocketState.Closed)
  101. {
  102. return;
  103. }
  104. _readyState = WebSocketState.CloseSent;
  105. }
  106. var e = new CloseEventArgs(payload)
  107. {
  108. WasClean = await CloseHandshakeAsync(
  109. send ? WebSocketFrame.CreateCloseFrame(Mask.Unmask, payload).ToByteArray() : null,
  110. wait ? 1000 : 0).ConfigureAwait(false)
  111. };
  112. _readyState = WebSocketState.Closed;
  113. try
  114. {
  115. OnClose.Emit(this, e);
  116. }
  117. catch (Exception ex)
  118. {
  119. error("An exception has occurred while OnClose.", ex);
  120. }
  121. }
  122. private async Task<bool> CloseHandshakeAsync(byte[] frameAsBytes, int millisecondsTimeout)
  123. {
  124. var sent = frameAsBytes != null && await WriteBytesAsync(frameAsBytes).ConfigureAwait(false);
  125. var received =
  126. millisecondsTimeout == 0 ||
  127. (sent && _exitReceiving != null && _exitReceiving.WaitOne(millisecondsTimeout));
  128. closeServerResources();
  129. if (_receivePong != null)
  130. {
  131. _receivePong.Dispose();
  132. _receivePong = null;
  133. }
  134. if (_exitReceiving != null)
  135. {
  136. _exitReceiving.Dispose();
  137. _exitReceiving = null;
  138. }
  139. var result = sent && received;
  140. return result;
  141. }
  142. // As server
  143. private void closeServerResources()
  144. {
  145. if (_closeContext == null)
  146. return;
  147. try
  148. {
  149. _closeContext();
  150. }
  151. catch (SocketException)
  152. {
  153. // it could be unable to send the handshake response
  154. }
  155. _closeContext = null;
  156. _stream = null;
  157. _context = null;
  158. }
  159. private async Task<bool> ConcatenateFragmentsIntoAsync(Stream dest)
  160. {
  161. while (true)
  162. {
  163. var frame = await WebSocketFrame.ReadAsync(_stream, true).ConfigureAwait(false);
  164. if (frame.IsFinal)
  165. {
  166. /* FINAL */
  167. // CONT
  168. if (frame.IsContinuation)
  169. {
  170. dest.WriteBytes(frame.PayloadData.ApplicationData);
  171. break;
  172. }
  173. // PING
  174. if (frame.IsPing)
  175. {
  176. processPingFrame(frame);
  177. continue;
  178. }
  179. // PONG
  180. if (frame.IsPong)
  181. {
  182. processPongFrame(frame);
  183. continue;
  184. }
  185. // CLOSE
  186. if (frame.IsClose)
  187. return await ProcessCloseFrameAsync(frame).ConfigureAwait(false);
  188. }
  189. else
  190. {
  191. /* MORE */
  192. // CONT
  193. if (frame.IsContinuation)
  194. {
  195. dest.WriteBytes(frame.PayloadData.ApplicationData);
  196. continue;
  197. }
  198. }
  199. // ?
  200. return await ProcessUnsupportedFrameAsync(
  201. frame,
  202. CloseStatusCode.IncorrectData,
  203. "An incorrect data has been received while receiving fragmented data.").ConfigureAwait(false);
  204. }
  205. return true;
  206. }
  207. // As server
  208. private HttpResponse createHandshakeCloseResponse(HttpStatusCode code)
  209. {
  210. var res = HttpResponse.CreateCloseResponse(code);
  211. res.Headers["Sec-WebSocket-Version"] = _version;
  212. return res;
  213. }
  214. private MessageEventArgs dequeueFromMessageEventQueue()
  215. {
  216. lock (_forMessageEventQueue)
  217. return _messageEventQueue.Count > 0
  218. ? _messageEventQueue.Dequeue()
  219. : null;
  220. }
  221. private void enqueueToMessageEventQueue(MessageEventArgs e)
  222. {
  223. lock (_forMessageEventQueue)
  224. _messageEventQueue.Enqueue(e);
  225. }
  226. private void error(string message, Exception exception)
  227. {
  228. try
  229. {
  230. if (exception != null)
  231. {
  232. message += ". Exception.Message: " + exception.Message;
  233. }
  234. OnError.Emit(this, new ErrorEventArgs(message));
  235. }
  236. catch (Exception)
  237. {
  238. }
  239. }
  240. private void error(string message)
  241. {
  242. try
  243. {
  244. OnError.Emit(this, new ErrorEventArgs(message));
  245. }
  246. catch (Exception)
  247. {
  248. }
  249. }
  250. private void init()
  251. {
  252. _compression = CompressionMethod.None;
  253. _cookies = new CookieCollection();
  254. _forConn = new object();
  255. _messageEventQueue = new Queue<MessageEventArgs>();
  256. _forMessageEventQueue = ((ICollection)_messageEventQueue).SyncRoot;
  257. _readyState = WebSocketState.Connecting;
  258. }
  259. private async Task OpenAsync()
  260. {
  261. try
  262. {
  263. startReceiving();
  264. }
  265. catch (Exception ex)
  266. {
  267. await ProcessExceptionAsync(ex, "An exception has occurred while opening.").ConfigureAwait(false);
  268. }
  269. await _forEvent.WaitAsync().ConfigureAwait(false);
  270. try
  271. {
  272. OnOpen?.Invoke(this, EventArgs.Empty);
  273. }
  274. catch (Exception ex)
  275. {
  276. await ProcessExceptionAsync(ex, "An exception has occurred while OnOpen.").ConfigureAwait(false);
  277. }
  278. finally
  279. {
  280. _forEvent.Release();
  281. }
  282. }
  283. private async Task<bool> ProcessCloseFrameAsync(WebSocketFrame frame)
  284. {
  285. var payload = frame.PayloadData;
  286. await CloseAsync(payload, !payload.ContainsReservedCloseStatusCode, false).ConfigureAwait(false);
  287. return false;
  288. }
  289. private bool processDataFrame(WebSocketFrame frame)
  290. {
  291. var e = frame.IsCompressed
  292. ? new MessageEventArgs(
  293. frame.Opcode, frame.PayloadData.ApplicationData.Decompress(_compression))
  294. : new MessageEventArgs(frame.Opcode, frame.PayloadData);
  295. enqueueToMessageEventQueue(e);
  296. return true;
  297. }
  298. private async Task ProcessExceptionAsync(Exception exception, string message)
  299. {
  300. var code = CloseStatusCode.Abnormal;
  301. var reason = message;
  302. if (exception is WebSocketException)
  303. {
  304. var wsex = (WebSocketException)exception;
  305. code = wsex.Code;
  306. reason = wsex.Message;
  307. }
  308. error(message ?? code.GetMessage(), exception);
  309. if (_readyState == WebSocketState.Connecting)
  310. {
  311. await CloseAsync(HttpStatusCode.BadRequest).ConfigureAwait(false);
  312. }
  313. else
  314. {
  315. await CloseAsync(code, reason ?? code.GetMessage(), false).ConfigureAwait(false);
  316. }
  317. }
  318. private Task<bool> ProcessFragmentedFrameAsync(WebSocketFrame frame)
  319. {
  320. return frame.IsContinuation // Not first fragment
  321. ? Task.FromResult(true)
  322. : ProcessFragmentsAsync(frame);
  323. }
  324. private async Task<bool> ProcessFragmentsAsync(WebSocketFrame first)
  325. {
  326. using (var buff = new MemoryStream())
  327. {
  328. buff.WriteBytes(first.PayloadData.ApplicationData);
  329. if (!await ConcatenateFragmentsIntoAsync(buff).ConfigureAwait(false))
  330. {
  331. return false;
  332. }
  333. byte[] data;
  334. if (_compression != CompressionMethod.None)
  335. {
  336. data = buff.DecompressToArray(_compression);
  337. }
  338. else
  339. {
  340. data = buff.ToArray();
  341. }
  342. enqueueToMessageEventQueue(new MessageEventArgs(first.Opcode, data));
  343. return true;
  344. }
  345. }
  346. private bool processPingFrame(WebSocketFrame frame)
  347. {
  348. return true;
  349. }
  350. private bool processPongFrame(WebSocketFrame frame)
  351. {
  352. _receivePong.Set();
  353. return true;
  354. }
  355. private async Task<bool> ProcessUnsupportedFrameAsync(WebSocketFrame frame, CloseStatusCode code, string reason)
  356. {
  357. await ProcessExceptionAsync(new WebSocketException(code, reason), null).ConfigureAwait(false);
  358. return false;
  359. }
  360. private Task<bool> ProcessWebSocketFrameAsync(WebSocketFrame frame)
  361. {
  362. // TODO: @bond change to if/else chain
  363. return frame.IsCompressed && _compression == CompressionMethod.None
  364. ? ProcessUnsupportedFrameAsync(
  365. frame,
  366. CloseStatusCode.IncorrectData,
  367. "A compressed data has been received without available decompression method.")
  368. : frame.IsFragmented
  369. ? ProcessFragmentedFrameAsync(frame)
  370. : frame.IsData
  371. ? Task.FromResult(processDataFrame(frame))
  372. : frame.IsPing
  373. ? Task.FromResult(processPingFrame(frame))
  374. : frame.IsPong
  375. ? Task.FromResult(processPongFrame(frame))
  376. : frame.IsClose
  377. ? ProcessCloseFrameAsync(frame)
  378. : ProcessUnsupportedFrameAsync(frame, CloseStatusCode.PolicyViolation, null);
  379. }
  380. private async Task<bool> SendAsync(Opcode opcode, Stream stream)
  381. {
  382. await _forSend.WaitAsync().ConfigureAwait(false);
  383. try
  384. {
  385. var src = stream;
  386. var compressed = false;
  387. var sent = false;
  388. try
  389. {
  390. if (_compression != CompressionMethod.None)
  391. {
  392. stream = stream.Compress(_compression);
  393. compressed = true;
  394. }
  395. sent = await SendAsync(opcode, Mask.Unmask, stream, compressed).ConfigureAwait(false);
  396. if (!sent)
  397. error("Sending a data has been interrupted.");
  398. }
  399. catch (Exception ex)
  400. {
  401. error("An exception has occurred while sending a data.", ex);
  402. }
  403. finally
  404. {
  405. if (compressed)
  406. stream.Dispose();
  407. src.Dispose();
  408. }
  409. return sent;
  410. }
  411. finally
  412. {
  413. _forSend.Release();
  414. }
  415. }
  416. private async Task<bool> SendAsync(Opcode opcode, Mask mask, Stream stream, bool compressed)
  417. {
  418. var len = stream.Length;
  419. /* Not fragmented */
  420. if (len == 0)
  421. return await SendAsync(Fin.Final, opcode, mask, new byte[0], compressed).ConfigureAwait(false);
  422. var quo = len / FragmentLength;
  423. var rem = (int)(len % FragmentLength);
  424. byte[] buff = null;
  425. if (quo == 0)
  426. {
  427. buff = new byte[rem];
  428. return await stream.ReadAsync(buff, 0, rem).ConfigureAwait(false) == rem &&
  429. await SendAsync(Fin.Final, opcode, mask, buff, compressed).ConfigureAwait(false);
  430. }
  431. buff = new byte[FragmentLength];
  432. if (quo == 1 && rem == 0)
  433. return await stream.ReadAsync(buff, 0, FragmentLength).ConfigureAwait(false) == FragmentLength &&
  434. await SendAsync(Fin.Final, opcode, mask, buff, compressed).ConfigureAwait(false);
  435. /* Send fragmented */
  436. // Begin
  437. if (await stream.ReadAsync(buff, 0, FragmentLength).ConfigureAwait(false) != FragmentLength ||
  438. !await SendAsync(Fin.More, opcode, mask, buff, compressed).ConfigureAwait(false))
  439. return false;
  440. var n = rem == 0 ? quo - 2 : quo - 1;
  441. for (long i = 0; i < n; i++)
  442. if (await stream.ReadAsync(buff, 0, FragmentLength).ConfigureAwait(false) != FragmentLength ||
  443. !await SendAsync(Fin.More, Opcode.Cont, mask, buff, compressed).ConfigureAwait(false))
  444. return false;
  445. // End
  446. if (rem == 0)
  447. rem = FragmentLength;
  448. else
  449. buff = new byte[rem];
  450. return await stream.ReadAsync(buff, 0, rem).ConfigureAwait(false) == rem &&
  451. await SendAsync(Fin.Final, Opcode.Cont, mask, buff, compressed).ConfigureAwait(false);
  452. }
  453. private Task<bool> SendAsync(Fin fin, Opcode opcode, Mask mask, byte[] data, bool compressed)
  454. {
  455. lock (_forConn)
  456. {
  457. if (_readyState != WebSocketState.Open)
  458. {
  459. return Task.FromResult(false);
  460. }
  461. return WriteBytesAsync(
  462. WebSocketFrame.CreateWebSocketFrame(fin, opcode, mask, data, compressed).ToByteArray());
  463. }
  464. }
  465. // As server
  466. private Task<bool> SendHttpResponseAsync(HttpResponse response)
  467. => WriteBytesAsync(response.ToByteArray());
  468. private void startReceiving()
  469. {
  470. if (_messageEventQueue.Count > 0)
  471. {
  472. _messageEventQueue.Clear();
  473. }
  474. _exitReceiving = new AutoResetEvent(false);
  475. _receivePong = new AutoResetEvent(false);
  476. Action receive = null;
  477. receive = async () => await WebSocketFrame.ReadAsync(
  478. _stream,
  479. true,
  480. async frame =>
  481. {
  482. if (await ProcessWebSocketFrameAsync(frame).ConfigureAwait(false) && _readyState != WebSocketState.Closed)
  483. {
  484. receive();
  485. if (!frame.IsData)
  486. {
  487. return;
  488. }
  489. await _forEvent.WaitAsync().ConfigureAwait(false);
  490. try
  491. {
  492. var e = dequeueFromMessageEventQueue();
  493. if (e != null && _readyState == WebSocketState.Open)
  494. {
  495. OnMessage.Emit(this, e);
  496. }
  497. }
  498. catch (Exception ex)
  499. {
  500. await ProcessExceptionAsync(ex, "An exception has occurred while OnMessage.").ConfigureAwait(false);
  501. }
  502. finally
  503. {
  504. _forEvent.Release();
  505. }
  506. }
  507. else if (_exitReceiving != null)
  508. {
  509. _exitReceiving.Set();
  510. }
  511. },
  512. async ex => await ProcessExceptionAsync(ex, "An exception has occurred while receiving a message.")).ConfigureAwait(false);
  513. receive();
  514. }
  515. private async Task<bool> WriteBytesAsync(byte[] data)
  516. {
  517. try
  518. {
  519. await _stream.WriteAsync(data, 0, data.Length).ConfigureAwait(false);
  520. return true;
  521. }
  522. catch (Exception)
  523. {
  524. return false;
  525. }
  526. }
  527. #endregion
  528. #region Internal Methods
  529. // As server
  530. internal async Task CloseAsync(HttpResponse response)
  531. {
  532. _readyState = WebSocketState.CloseSent;
  533. await SendHttpResponseAsync(response).ConfigureAwait(false);
  534. closeServerResources();
  535. _readyState = WebSocketState.Closed;
  536. }
  537. // As server
  538. internal Task CloseAsync(HttpStatusCode code)
  539. => CloseAsync(createHandshakeCloseResponse(code));
  540. // As server
  541. public async Task ConnectAsServer()
  542. {
  543. try
  544. {
  545. _readyState = WebSocketState.Open;
  546. await OpenAsync().ConfigureAwait(false);
  547. }
  548. catch (Exception ex)
  549. {
  550. await ProcessExceptionAsync(ex, "An exception has occurred while connecting.").ConfigureAwait(false);
  551. }
  552. }
  553. #endregion
  554. #region Public Methods
  555. /// <summary>
  556. /// Closes the WebSocket connection, and releases all associated resources.
  557. /// </summary>
  558. public Task CloseAsync()
  559. {
  560. var msg = _readyState.CheckIfClosable();
  561. if (msg != null)
  562. {
  563. error(msg);
  564. return Task.CompletedTask;
  565. }
  566. var send = _readyState == WebSocketState.Open;
  567. return CloseAsync(new PayloadData(), send, send);
  568. }
  569. /// <summary>
  570. /// Closes the WebSocket connection with the specified <see cref="CloseStatusCode"/>
  571. /// and <see cref="string"/>, and releases all associated resources.
  572. /// </summary>
  573. /// <remarks>
  574. /// This method emits a <see cref="OnError"/> event if the size
  575. /// of <paramref name="reason"/> is greater than 123 bytes.
  576. /// </remarks>
  577. /// <param name="code">
  578. /// One of the <see cref="CloseStatusCode"/> enum values, represents the status code
  579. /// indicating the reason for the close.
  580. /// </param>
  581. /// <param name="reason">
  582. /// A <see cref="string"/> that represents the reason for the close.
  583. /// </param>
  584. public async Task CloseAsync(CloseStatusCode code, string reason)
  585. {
  586. byte[] data = null;
  587. var msg = _readyState.CheckIfClosable() ??
  588. (data = await ((ushort)code).AppendAsync(reason).ConfigureAwait(false)).CheckIfValidControlData("reason");
  589. if (msg != null)
  590. {
  591. error(msg);
  592. return;
  593. }
  594. var send = _readyState == WebSocketState.Open && !code.IsReserved();
  595. await CloseAsync(new PayloadData(data), send, send).ConfigureAwait(false);
  596. }
  597. /// <summary>
  598. /// Sends a binary <paramref name="data"/> asynchronously using the WebSocket connection.
  599. /// </summary>
  600. /// <remarks>
  601. /// This method doesn't wait for the send to be complete.
  602. /// </remarks>
  603. /// <param name="data">
  604. /// An array of <see cref="byte"/> that represents the binary data to send.
  605. /// </param>
  606. public Task SendAsync(byte[] data)
  607. {
  608. if (data == null)
  609. {
  610. throw new ArgumentNullException(nameof(data));
  611. }
  612. var msg = _readyState.CheckIfOpen();
  613. if (msg != null)
  614. {
  615. throw new Exception(msg);
  616. }
  617. return SendAsync(Opcode.Binary, new MemoryStream(data));
  618. }
  619. /// <summary>
  620. /// Sends a text <paramref name="data"/> asynchronously using the WebSocket connection.
  621. /// </summary>
  622. /// <remarks>
  623. /// This method doesn't wait for the send to be complete.
  624. /// </remarks>
  625. /// <param name="data">
  626. /// A <see cref="string"/> that represents the text data to send.
  627. /// </param>
  628. public Task SendAsync(string data)
  629. {
  630. if (data == null)
  631. {
  632. throw new ArgumentNullException(nameof(data));
  633. }
  634. var msg = _readyState.CheckIfOpen();
  635. if (msg != null)
  636. {
  637. throw new Exception(msg);
  638. }
  639. return SendAsync(Opcode.Text, new MemoryStream(Encoding.UTF8.GetBytes(data)));
  640. }
  641. #endregion
  642. #region Explicit Interface Implementation
  643. /// <summary>
  644. /// Closes the WebSocket connection, and releases all associated resources.
  645. /// </summary>
  646. /// <remarks>
  647. /// This method closes the WebSocket connection with <see cref="CloseStatusCode.Away"/>.
  648. /// </remarks>
  649. void IDisposable.Dispose()
  650. {
  651. CloseAsync(CloseStatusCode.Away, null).GetAwaiter().GetResult();
  652. }
  653. #endregion
  654. }
  655. }