WebSocket.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  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. // TODO: @bond change to if/else chain
  364. return frame.IsCompressed && _compression == CompressionMethod.None
  365. ? ProcessUnsupportedFrameAsync(
  366. frame,
  367. CloseStatusCode.IncorrectData,
  368. "A compressed data has been received without available decompression method.")
  369. : frame.IsFragmented
  370. ? ProcessFragmentedFrameAsync(frame)
  371. : frame.IsData
  372. ? Task.FromResult(processDataFrame(frame))
  373. : frame.IsPing
  374. ? Task.FromResult(processPingFrame(frame))
  375. : frame.IsPong
  376. ? Task.FromResult(processPongFrame(frame))
  377. : frame.IsClose
  378. ? ProcessCloseFrameAsync(frame)
  379. : ProcessUnsupportedFrameAsync(frame, CloseStatusCode.PolicyViolation, null);
  380. }
  381. private async Task<bool> SendAsync(Opcode opcode, Stream stream)
  382. {
  383. await _forSend.WaitAsync().ConfigureAwait(false);
  384. try
  385. {
  386. var src = stream;
  387. var compressed = false;
  388. var sent = false;
  389. try
  390. {
  391. if (_compression != CompressionMethod.None)
  392. {
  393. stream = stream.Compress(_compression);
  394. compressed = true;
  395. }
  396. sent = await SendAsync(opcode, Mask.Unmask, stream, compressed).ConfigureAwait(false);
  397. if (!sent)
  398. error("Sending a data has been interrupted.");
  399. }
  400. catch (Exception ex)
  401. {
  402. error("An exception has occurred while sending a data.", ex);
  403. }
  404. finally
  405. {
  406. if (compressed)
  407. stream.Dispose();
  408. src.Dispose();
  409. }
  410. return sent;
  411. }
  412. finally
  413. {
  414. _forSend.Release();
  415. }
  416. }
  417. private async Task<bool> SendAsync(Opcode opcode, Mask mask, Stream stream, bool compressed)
  418. {
  419. var len = stream.Length;
  420. /* Not fragmented */
  421. if (len == 0)
  422. return await SendAsync(Fin.Final, opcode, mask, new byte[0], compressed).ConfigureAwait(false);
  423. var quo = len / FragmentLength;
  424. var rem = (int)(len % FragmentLength);
  425. byte[] buff = null;
  426. if (quo == 0)
  427. {
  428. buff = new byte[rem];
  429. return await stream.ReadAsync(buff, 0, rem).ConfigureAwait(false) == rem &&
  430. await SendAsync(Fin.Final, opcode, mask, buff, compressed).ConfigureAwait(false);
  431. }
  432. buff = new byte[FragmentLength];
  433. if (quo == 1 && rem == 0)
  434. return await stream.ReadAsync(buff, 0, FragmentLength).ConfigureAwait(false) == FragmentLength &&
  435. await SendAsync(Fin.Final, opcode, mask, buff, compressed).ConfigureAwait(false);
  436. /* Send fragmented */
  437. // Begin
  438. if (await stream.ReadAsync(buff, 0, FragmentLength).ConfigureAwait(false) != FragmentLength ||
  439. !await SendAsync(Fin.More, opcode, mask, buff, compressed).ConfigureAwait(false))
  440. return false;
  441. var n = rem == 0 ? quo - 2 : quo - 1;
  442. for (long i = 0; i < n; i++)
  443. if (await stream.ReadAsync(buff, 0, FragmentLength).ConfigureAwait(false) != FragmentLength ||
  444. !await SendAsync(Fin.More, Opcode.Cont, mask, buff, compressed).ConfigureAwait(false))
  445. return false;
  446. // End
  447. if (rem == 0)
  448. rem = FragmentLength;
  449. else
  450. buff = new byte[rem];
  451. return await stream.ReadAsync(buff, 0, rem).ConfigureAwait(false) == rem &&
  452. await SendAsync(Fin.Final, Opcode.Cont, mask, buff, compressed).ConfigureAwait(false);
  453. }
  454. private Task<bool> SendAsync(Fin fin, Opcode opcode, Mask mask, byte[] data, bool compressed)
  455. {
  456. lock (_forConn)
  457. {
  458. if (_readyState != WebSocketState.Open)
  459. {
  460. return Task.FromResult(false);
  461. }
  462. return WriteBytesAsync(
  463. WebSocketFrame.CreateWebSocketFrame(fin, opcode, mask, data, compressed).ToByteArray());
  464. }
  465. }
  466. // As server
  467. private Task<bool> SendHttpResponseAsync(HttpResponse response)
  468. => WriteBytesAsync(response.ToByteArray());
  469. private void startReceiving()
  470. {
  471. if (_messageEventQueue.Count > 0)
  472. {
  473. _messageEventQueue.Clear();
  474. }
  475. _exitReceiving = new AutoResetEvent(false);
  476. _receivePong = new AutoResetEvent(false);
  477. Action receive = null;
  478. receive = async () => await WebSocketFrame.ReadAsync(
  479. _stream,
  480. true,
  481. async frame =>
  482. {
  483. if (await ProcessWebSocketFrameAsync(frame).ConfigureAwait(false) && _readyState != WebSocketState.Closed)
  484. {
  485. receive();
  486. if (!frame.IsData)
  487. {
  488. return;
  489. }
  490. await _forEvent.WaitAsync().ConfigureAwait(false);
  491. try
  492. {
  493. var e = dequeueFromMessageEventQueue();
  494. if (e != null && _readyState == WebSocketState.Open)
  495. {
  496. OnMessage.Emit(this, e);
  497. }
  498. }
  499. catch (Exception ex)
  500. {
  501. await ProcessExceptionAsync(ex, "An exception has occurred while OnMessage.").ConfigureAwait(false);
  502. }
  503. finally
  504. {
  505. _forEvent.Release();
  506. }
  507. }
  508. else if (_exitReceiving != null)
  509. {
  510. _exitReceiving.Set();
  511. }
  512. },
  513. async ex => await ProcessExceptionAsync(ex, "An exception has occurred while receiving a message.")).ConfigureAwait(false);
  514. receive();
  515. }
  516. private async Task<bool> WriteBytesAsync(byte[] data)
  517. {
  518. try
  519. {
  520. await _stream.WriteAsync(data, 0, data.Length).ConfigureAwait(false);
  521. return true;
  522. }
  523. catch (Exception)
  524. {
  525. return false;
  526. }
  527. }
  528. #endregion
  529. #region Internal Methods
  530. // As server
  531. internal async Task CloseAsync(HttpResponse response)
  532. {
  533. _readyState = WebSocketState.CloseSent;
  534. await SendHttpResponseAsync(response).ConfigureAwait(false);
  535. closeServerResources();
  536. _readyState = WebSocketState.Closed;
  537. }
  538. // As server
  539. internal Task CloseAsync(HttpStatusCode code)
  540. => CloseAsync(createHandshakeCloseResponse(code));
  541. // As server
  542. public async Task ConnectAsServer()
  543. {
  544. try
  545. {
  546. _readyState = WebSocketState.Open;
  547. await OpenAsync().ConfigureAwait(false);
  548. }
  549. catch (Exception ex)
  550. {
  551. await ProcessExceptionAsync(ex, "An exception has occurred while connecting.").ConfigureAwait(false);
  552. }
  553. }
  554. #endregion
  555. #region Public Methods
  556. /// <summary>
  557. /// Closes the WebSocket connection, and releases all associated resources.
  558. /// </summary>
  559. public Task CloseAsync()
  560. {
  561. var msg = _readyState.CheckIfClosable();
  562. if (msg != null)
  563. {
  564. error(msg);
  565. return Task.CompletedTask;
  566. }
  567. var send = _readyState == WebSocketState.Open;
  568. return CloseAsync(new PayloadData(), send, send);
  569. }
  570. /// <summary>
  571. /// Closes the WebSocket connection with the specified <see cref="CloseStatusCode"/>
  572. /// and <see cref="string"/>, and releases all associated resources.
  573. /// </summary>
  574. /// <remarks>
  575. /// This method emits a <see cref="OnError"/> event if the size
  576. /// of <paramref name="reason"/> is greater than 123 bytes.
  577. /// </remarks>
  578. /// <param name="code">
  579. /// One of the <see cref="CloseStatusCode"/> enum values, represents the status code
  580. /// indicating the reason for the close.
  581. /// </param>
  582. /// <param name="reason">
  583. /// A <see cref="string"/> that represents the reason for the close.
  584. /// </param>
  585. public async Task CloseAsync(CloseStatusCode code, string reason)
  586. {
  587. byte[] data = null;
  588. var msg = _readyState.CheckIfClosable() ??
  589. (data = await ((ushort)code).AppendAsync(reason).ConfigureAwait(false)).CheckIfValidControlData("reason");
  590. if (msg != null)
  591. {
  592. error(msg);
  593. return;
  594. }
  595. var send = _readyState == WebSocketState.Open && !code.IsReserved();
  596. await CloseAsync(new PayloadData(data), send, send).ConfigureAwait(false);
  597. }
  598. /// <summary>
  599. /// Sends a binary <paramref name="data"/> asynchronously using the WebSocket connection.
  600. /// </summary>
  601. /// <remarks>
  602. /// This method doesn't wait for the send to be complete.
  603. /// </remarks>
  604. /// <param name="data">
  605. /// An array of <see cref="byte"/> that represents the binary data to send.
  606. /// </param>
  607. public Task SendAsync(byte[] data)
  608. {
  609. if (data == null)
  610. {
  611. throw new ArgumentNullException(nameof(data));
  612. }
  613. var msg = _readyState.CheckIfOpen();
  614. if (msg != null)
  615. {
  616. throw new Exception(msg);
  617. }
  618. return SendAsync(Opcode.Binary, new MemoryStream(data));
  619. }
  620. /// <summary>
  621. /// Sends a text <paramref name="data"/> asynchronously using the WebSocket connection.
  622. /// </summary>
  623. /// <remarks>
  624. /// This method doesn't wait for the send to be complete.
  625. /// </remarks>
  626. /// <param name="data">
  627. /// A <see cref="string"/> that represents the text data to send.
  628. /// </param>
  629. public Task SendAsync(string data)
  630. {
  631. if (data == null)
  632. {
  633. throw new ArgumentNullException(nameof(data));
  634. }
  635. var msg = _readyState.CheckIfOpen();
  636. if (msg != null)
  637. {
  638. throw new Exception(msg);
  639. }
  640. return SendAsync(Opcode.Text, new MemoryStream(Encoding.UTF8.GetBytes(data)));
  641. }
  642. #endregion
  643. #region Explicit Interface Implementation
  644. /// <summary>
  645. /// Closes the WebSocket connection, and releases all associated resources.
  646. /// </summary>
  647. /// <remarks>
  648. /// This method closes the WebSocket connection with <see cref="CloseStatusCode.Away"/>.
  649. /// </remarks>
  650. void IDisposable.Dispose()
  651. {
  652. CloseAsync(CloseStatusCode.Away, null).GetAwaiter().GetResult();
  653. }
  654. #endregion
  655. }
  656. }