WebSocket.cs 28 KB

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