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.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using SocketHttpListener.Net.WebSockets;
  11. using HttpStatusCode = SocketHttpListener.Net.HttpStatusCode;
  12. using WebSocketState = System.Net.WebSockets.WebSocketState;
  13. namespace SocketHttpListener
  14. {
  15. /// <summary>
  16. /// Implements the WebSocket interface.
  17. /// </summary>
  18. /// <remarks>
  19. /// The WebSocket class provides a set of methods and properties for two-way communication using
  20. /// the WebSocket protocol (<see href="http://tools.ietf.org/html/rfc6455">RFC 6455</see>).
  21. /// </remarks>
  22. public class WebSocket : IDisposable
  23. {
  24. #region Private Fields
  25. private Action _closeContext;
  26. private CompressionMethod _compression;
  27. private WebSocketContext _context;
  28. private CookieCollection _cookies;
  29. private AutoResetEvent _exitReceiving;
  30. private object _forConn;
  31. private readonly SemaphoreSlim _forEvent = new SemaphoreSlim(1, 1);
  32. private object _forMessageEventQueue;
  33. private readonly SemaphoreSlim _forSend = new SemaphoreSlim(1, 1);
  34. private const string _guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  35. private Queue<MessageEventArgs> _messageEventQueue;
  36. private string _protocol;
  37. private volatile WebSocketState _readyState;
  38. private AutoResetEvent _receivePong;
  39. private bool _secure;
  40. private Stream _stream;
  41. private const string _version = "13";
  42. #endregion
  43. #region Internal Fields
  44. internal const int FragmentLength = 1016; // Max value is int.MaxValue - 14.
  45. #endregion
  46. #region Internal Constructors
  47. // As server
  48. internal WebSocket(string protocol)
  49. {
  50. _protocol = protocol;
  51. }
  52. public void SetContext(HttpListenerWebSocketContext context, Action closeContextFn, Stream stream)
  53. {
  54. _context = context;
  55. _closeContext = closeContextFn;
  56. _secure = context.IsSecureConnection;
  57. _stream = stream;
  58. init();
  59. }
  60. // In the .NET Framework, this pulls the value from a P/Invoke. Here we just hardcode it to a reasonable default.
  61. public static TimeSpan DefaultKeepAliveInterval => TimeSpan.FromSeconds(30);
  62. #endregion
  63. /// <summary>
  64. /// Gets the state of the WebSocket connection.
  65. /// </summary>
  66. /// <value>
  67. /// One of the <see cref="WebSocketState"/> enum values, indicates the state of the WebSocket
  68. /// connection. The default value is <see cref="WebSocketState.Connecting"/>.
  69. /// </value>
  70. public WebSocketState ReadyState => _readyState;
  71. #region Public Events
  72. /// <summary>
  73. /// Occurs when the WebSocket connection has been closed.
  74. /// </summary>
  75. public event EventHandler<CloseEventArgs> OnClose;
  76. /// <summary>
  77. /// Occurs when the <see cref="WebSocket"/> gets an error.
  78. /// </summary>
  79. public event EventHandler<ErrorEventArgs> OnError;
  80. /// <summary>
  81. /// Occurs when the <see cref="WebSocket"/> receives a message.
  82. /// </summary>
  83. public event EventHandler<MessageEventArgs> OnMessage;
  84. /// <summary>
  85. /// Occurs when the WebSocket connection has been established.
  86. /// </summary>
  87. public event EventHandler OnOpen;
  88. #endregion
  89. #region Private Methods
  90. private async Task CloseAsync(CloseStatusCode code, string reason, bool wait)
  91. {
  92. await CloseAsync(new PayloadData(
  93. await ((ushort)code).AppendAsync(reason).ConfigureAwait(false)),
  94. !code.IsReserved(),
  95. wait).ConfigureAwait(false);
  96. }
  97. private async Task CloseAsync(PayloadData payload, bool send, bool wait)
  98. {
  99. lock (_forConn)
  100. {
  101. if (_readyState == WebSocketState.CloseSent || _readyState == WebSocketState.Closed)
  102. {
  103. return;
  104. }
  105. _readyState = WebSocketState.CloseSent;
  106. }
  107. var e = new CloseEventArgs(payload)
  108. {
  109. WasClean = await CloseHandshakeAsync(
  110. send ? WebSocketFrame.CreateCloseFrame(Mask.Unmask, payload).ToByteArray() : null,
  111. wait ? 1000 : 0).ConfigureAwait(false)
  112. };
  113. _readyState = WebSocketState.Closed;
  114. try
  115. {
  116. OnClose.Emit(this, e);
  117. }
  118. catch (Exception ex)
  119. {
  120. error("An exception has occurred while OnClose.", ex);
  121. }
  122. }
  123. private async Task<bool> CloseHandshakeAsync(byte[] frameAsBytes, int millisecondsTimeout)
  124. {
  125. var sent = frameAsBytes != null && await WriteBytesAsync(frameAsBytes).ConfigureAwait(false);
  126. var received =
  127. millisecondsTimeout == 0 ||
  128. (sent && _exitReceiving != null && _exitReceiving.WaitOne(millisecondsTimeout));
  129. closeServerResources();
  130. if (_receivePong != null)
  131. {
  132. _receivePong.Dispose();
  133. _receivePong = null;
  134. }
  135. if (_exitReceiving != null)
  136. {
  137. _exitReceiving.Dispose();
  138. _exitReceiving = null;
  139. }
  140. var result = sent && received;
  141. return result;
  142. }
  143. // As server
  144. private void closeServerResources()
  145. {
  146. if (_closeContext == null)
  147. return;
  148. try
  149. {
  150. _closeContext();
  151. }
  152. catch (SocketException)
  153. {
  154. // it could be unable to send the handshake response
  155. }
  156. _closeContext = null;
  157. _stream = null;
  158. _context = null;
  159. }
  160. private async Task<bool> ConcatenateFragmentsIntoAsync(Stream dest)
  161. {
  162. while (true)
  163. {
  164. var frame = await WebSocketFrame.ReadAsync(_stream, true).ConfigureAwait(false);
  165. if (frame.IsFinal)
  166. {
  167. /* FINAL */
  168. // CONT
  169. if (frame.IsContinuation)
  170. {
  171. dest.WriteBytes(frame.PayloadData.ApplicationData);
  172. break;
  173. }
  174. // PING
  175. if (frame.IsPing)
  176. {
  177. processPingFrame(frame);
  178. continue;
  179. }
  180. // PONG
  181. if (frame.IsPong)
  182. {
  183. processPongFrame(frame);
  184. continue;
  185. }
  186. // CLOSE
  187. if (frame.IsClose)
  188. return await ProcessCloseFrameAsync(frame).ConfigureAwait(false);
  189. }
  190. else
  191. {
  192. /* MORE */
  193. // CONT
  194. if (frame.IsContinuation)
  195. {
  196. dest.WriteBytes(frame.PayloadData.ApplicationData);
  197. continue;
  198. }
  199. }
  200. // ?
  201. return await ProcessUnsupportedFrameAsync(
  202. frame,
  203. CloseStatusCode.IncorrectData,
  204. "An incorrect data has been received while receiving fragmented data.").ConfigureAwait(false);
  205. }
  206. return true;
  207. }
  208. // As server
  209. private HttpResponse createHandshakeCloseResponse(HttpStatusCode code)
  210. {
  211. var res = HttpResponse.CreateCloseResponse(code);
  212. res.Headers["Sec-WebSocket-Version"] = _version;
  213. return res;
  214. }
  215. private MessageEventArgs dequeueFromMessageEventQueue()
  216. {
  217. lock (_forMessageEventQueue)
  218. return _messageEventQueue.Count > 0
  219. ? _messageEventQueue.Dequeue()
  220. : null;
  221. }
  222. private void enqueueToMessageEventQueue(MessageEventArgs e)
  223. {
  224. lock (_forMessageEventQueue)
  225. _messageEventQueue.Enqueue(e);
  226. }
  227. private void error(string message, Exception exception)
  228. {
  229. try
  230. {
  231. if (exception != null)
  232. {
  233. message += ". Exception.Message: " + exception.Message;
  234. }
  235. OnError.Emit(this, new ErrorEventArgs(message));
  236. }
  237. catch (Exception)
  238. {
  239. }
  240. }
  241. private void error(string message)
  242. {
  243. try
  244. {
  245. OnError.Emit(this, new ErrorEventArgs(message));
  246. }
  247. catch (Exception)
  248. {
  249. }
  250. }
  251. private void init()
  252. {
  253. _compression = CompressionMethod.None;
  254. _cookies = new CookieCollection();
  255. _forConn = new object();
  256. _messageEventQueue = new Queue<MessageEventArgs>();
  257. _forMessageEventQueue = ((ICollection)_messageEventQueue).SyncRoot;
  258. _readyState = WebSocketState.Connecting;
  259. }
  260. private async Task OpenAsync()
  261. {
  262. try
  263. {
  264. startReceiving();
  265. }
  266. catch (Exception ex)
  267. {
  268. await ProcessExceptionAsync(ex, "An exception has occurred while opening.").ConfigureAwait(false);
  269. }
  270. await _forEvent.WaitAsync().ConfigureAwait(false);
  271. try
  272. {
  273. OnOpen?.Invoke(this, EventArgs.Empty);
  274. }
  275. catch (Exception ex)
  276. {
  277. await ProcessExceptionAsync(ex, "An exception has occurred while OnOpen.").ConfigureAwait(false);
  278. }
  279. finally
  280. {
  281. _forEvent.Release();
  282. }
  283. }
  284. private async Task<bool> ProcessCloseFrameAsync(WebSocketFrame frame)
  285. {
  286. var payload = frame.PayloadData;
  287. await CloseAsync(payload, !payload.ContainsReservedCloseStatusCode, false).ConfigureAwait(false);
  288. return false;
  289. }
  290. private bool processDataFrame(WebSocketFrame frame)
  291. {
  292. var e = frame.IsCompressed
  293. ? new MessageEventArgs(
  294. frame.Opcode, frame.PayloadData.ApplicationData.Decompress(_compression))
  295. : new MessageEventArgs(frame.Opcode, frame.PayloadData);
  296. enqueueToMessageEventQueue(e);
  297. return true;
  298. }
  299. private async Task ProcessExceptionAsync(Exception exception, string message)
  300. {
  301. var code = CloseStatusCode.Abnormal;
  302. var reason = message;
  303. if (exception is WebSocketException)
  304. {
  305. var wsex = (WebSocketException)exception;
  306. code = wsex.Code;
  307. reason = wsex.Message;
  308. }
  309. error(message ?? code.GetMessage(), exception);
  310. if (_readyState == WebSocketState.Connecting)
  311. {
  312. await CloseAsync(HttpStatusCode.BadRequest).ConfigureAwait(false);
  313. }
  314. else
  315. {
  316. await CloseAsync(code, reason ?? code.GetMessage(), false).ConfigureAwait(false);
  317. }
  318. }
  319. private Task<bool> ProcessFragmentedFrameAsync(WebSocketFrame frame)
  320. {
  321. return frame.IsContinuation // Not first fragment
  322. ? Task.FromResult(true)
  323. : ProcessFragmentsAsync(frame);
  324. }
  325. private async Task<bool> ProcessFragmentsAsync(WebSocketFrame first)
  326. {
  327. using (var buff = new MemoryStream())
  328. {
  329. buff.WriteBytes(first.PayloadData.ApplicationData);
  330. if (!await ConcatenateFragmentsIntoAsync(buff).ConfigureAwait(false))
  331. {
  332. return false;
  333. }
  334. byte[] data;
  335. if (_compression != CompressionMethod.None)
  336. {
  337. data = buff.DecompressToArray(_compression);
  338. }
  339. else
  340. {
  341. data = buff.ToArray();
  342. }
  343. enqueueToMessageEventQueue(new MessageEventArgs(first.Opcode, data));
  344. return true;
  345. }
  346. }
  347. private bool processPingFrame(WebSocketFrame frame)
  348. {
  349. return true;
  350. }
  351. private bool processPongFrame(WebSocketFrame frame)
  352. {
  353. _receivePong.Set();
  354. return true;
  355. }
  356. private async Task<bool> ProcessUnsupportedFrameAsync(WebSocketFrame frame, CloseStatusCode code, string reason)
  357. {
  358. await ProcessExceptionAsync(new WebSocketException(code, reason), null).ConfigureAwait(false);
  359. return false;
  360. }
  361. private Task<bool> ProcessWebSocketFrameAsync(WebSocketFrame frame)
  362. {
  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. }