2
0

WebSocket.cs 27 KB

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