WebSocket.cs 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529
  1. #region MIT License
  2. /**
  3. * WebSocket.cs
  4. *
  5. * A C# implementation of the WebSocket interface.
  6. * This code derived from WebSocket.java (http://github.com/adamac/Java-WebSocket-client).
  7. *
  8. * The MIT License
  9. *
  10. * Copyright (c) 2009 Adam MacBeth
  11. * Copyright (c) 2010-2012 sta.blockhead
  12. *
  13. * Permission is hereby granted, free of charge, to any person obtaining a copy
  14. * of this software and associated documentation files (the "Software"), to deal
  15. * in the Software without restriction, including without limitation the rights
  16. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17. * copies of the Software, and to permit persons to whom the Software is
  18. * furnished to do so, subject to the following conditions:
  19. *
  20. * The above copyright notice and this permission notice shall be included in
  21. * all copies or substantial portions of the Software.
  22. *
  23. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  24. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  25. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  26. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  27. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  28. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  29. * THE SOFTWARE.
  30. */
  31. #endregion
  32. using System;
  33. using System.Collections.Generic;
  34. using System.Collections.Specialized;
  35. using System.Diagnostics;
  36. using System.IO;
  37. using System.Net.Sockets;
  38. using System.Security.Cryptography;
  39. using System.Text;
  40. using System.Threading;
  41. using WebSocketSharp.Frame;
  42. using WebSocketSharp.Net;
  43. using WebSocketSharp.Net.Sockets;
  44. namespace WebSocketSharp
  45. {
  46. /// <summary>
  47. /// Implements the WebSocket interface.
  48. /// </summary>
  49. /// <remarks>
  50. /// The WebSocket class provides methods and properties for two-way communication using the WebSocket protocol (RFC 6455).
  51. /// </remarks>
  52. public class WebSocket : IDisposable
  53. {
  54. #region Private Const Fields
  55. private const int _fragmentLen = 1016; // Max value is int.MaxValue - 14.
  56. private const string _guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  57. private const string _version = "13";
  58. #endregion
  59. #region Private Fields
  60. private string _base64key;
  61. private HttpListenerContext _httpContext;
  62. private WebSocketContext _context;
  63. private System.Net.IPEndPoint _endPoint;
  64. private string _extensions;
  65. private AutoResetEvent _exitMessageLoop;
  66. private Object _forClose;
  67. private Object _forSend;
  68. private bool _isClient;
  69. private bool _isSecure;
  70. private string _protocol;
  71. private string _protocols;
  72. private NameValueCollection _queryString;
  73. private volatile WsState _readyState;
  74. private AutoResetEvent _receivePong;
  75. private TcpClient _tcpClient;
  76. private Uri _uri;
  77. private SynchronizedCollection<WsFrame> _unTransmittedBuffer;
  78. private WsStream _wsStream;
  79. private string _origin;
  80. #endregion
  81. #region Private Constructor
  82. private WebSocket()
  83. {
  84. _extensions = String.Empty;
  85. _forClose = new Object();
  86. _forSend = new Object();
  87. _protocol = String.Empty;
  88. _readyState = WsState.CONNECTING;
  89. _unTransmittedBuffer = new SynchronizedCollection<WsFrame>();
  90. }
  91. #endregion
  92. #region Internal Constructor
  93. internal WebSocket(HttpListenerWebSocketContext context)
  94. : this()
  95. {
  96. _uri = Ext.ToUri(context.Path);
  97. _context = context;
  98. _httpContext = context.BaseContext;
  99. _wsStream = context.Stream;
  100. _endPoint = context.ServerEndPoint;
  101. _isClient = false;
  102. _isSecure = context.IsSecureConnection;
  103. }
  104. internal WebSocket(TcpListenerWebSocketContext context)
  105. : this()
  106. {
  107. _uri = Ext.ToUri(context.Path);
  108. _context = context;
  109. _tcpClient = context.Client;
  110. _wsStream = context.Stream;
  111. _endPoint = context.ServerEndPoint;
  112. _isClient = false;
  113. _isSecure = context.IsSecureConnection;
  114. }
  115. #endregion
  116. #region Public Constructors
  117. /// <summary>
  118. /// Initializes a new instance of the <see cref="WebSocketSharp.WebSocket"/> class with the specified WebSocket URL and subprotocols.
  119. /// </summary>
  120. /// <param name="url">
  121. /// A <see cref="string"/> that contains the WebSocket URL.
  122. /// </param>
  123. /// <param name="protocols">
  124. /// An array of <see cref="string"/> that contains the WebSocket subprotocols if any.
  125. /// </param>
  126. /// <exception cref="ArgumentNullException">
  127. /// <paramref name="url"/> is <see langword="null"/>.
  128. /// </exception>
  129. /// <exception cref="ArgumentException">
  130. /// <paramref name="url"/> is not valid WebSocket URL.
  131. /// </exception>
  132. public WebSocket(string url, params string[] protocols)
  133. : this()
  134. {
  135. if (url == null)
  136. throw new ArgumentNullException("url");
  137. Uri uri;
  138. string msg;
  139. if (!tryCreateUri(url, out uri, out msg))
  140. throw new ArgumentException(msg, "url");
  141. _uri = uri;
  142. _protocols = Ext.ToString(protocols, ", ");
  143. _base64key = createBase64Key();
  144. _isClient = true;
  145. _isSecure = uri.Scheme == "wss" ? true : false;
  146. }
  147. /// <summary>
  148. /// Initializes a new instance of the <see cref="WebSocketSharp.WebSocket"/> class with the specified WebSocket URL, OnOpen, OnMessage, OnError, OnClose event handlers and subprotocols.
  149. /// </summary>
  150. /// <param name="url">
  151. /// A <see cref="string"/> that contains the WebSocket URL.
  152. /// </param>
  153. /// <param name="onOpen">
  154. /// An OnOpen event handler.
  155. /// </param>
  156. /// <param name="onMessage">
  157. /// An OnMessage event handler.
  158. /// </param>
  159. /// <param name="onError">
  160. /// An OnError event handler.
  161. /// </param>
  162. /// <param name="onClose">
  163. /// An OnClose event handler.
  164. /// </param>
  165. /// <param name="protocols">
  166. /// An array of <see cref="string"/> that contains the WebSocket subprotocols if any.
  167. /// </param>
  168. /// <exception cref="ArgumentNullException">
  169. /// <paramref name="url"/> is <see langword="null"/>.
  170. /// </exception>
  171. /// <exception cref="ArgumentException">
  172. /// <paramref name="url"/> is not valid WebSocket URL.
  173. /// </exception>
  174. public WebSocket(
  175. string url,
  176. EventHandler onOpen,
  177. EventHandler<MessageEventArgs> onMessage,
  178. EventHandler<ErrorEventArgs> onError,
  179. EventHandler<CloseEventArgs> onClose,
  180. params string[] protocols)
  181. : this(url, protocols)
  182. {
  183. OnOpen = onOpen;
  184. OnMessage = onMessage;
  185. OnError = onError;
  186. OnClose = onClose;
  187. Connect();
  188. }
  189. #endregion
  190. #region Internal Property
  191. internal NameValueCollection QueryString
  192. {
  193. get
  194. {
  195. return _queryString;
  196. }
  197. }
  198. #endregion
  199. #region Public Properties
  200. /// <summary>
  201. /// Gets the amount of untransmitted data.
  202. /// </summary>
  203. /// <value>
  204. /// The number of bytes of untransmitted data.
  205. /// </value>
  206. public ulong BufferedAmount
  207. {
  208. get
  209. {
  210. lock (_unTransmittedBuffer.SyncRoot)
  211. {
  212. ulong bufferedAmount = 0;
  213. foreach (WsFrame frame in _unTransmittedBuffer)
  214. bufferedAmount += frame.PayloadLength;
  215. return bufferedAmount;
  216. }
  217. }
  218. }
  219. /// <summary>
  220. /// Gets the extensions selected by the server.
  221. /// </summary>
  222. /// <value>
  223. /// A <see cref="string"/> that contains the extensions if any. By default, <c>String.Empty</c>. (Currently this will only ever be the <c>String.Empty</c>.)
  224. /// </value>
  225. public string Extensions
  226. {
  227. get
  228. {
  229. return _extensions;
  230. }
  231. }
  232. /// <summary>
  233. /// Gets a value indicating whether a connection is alive.
  234. /// </summary>
  235. /// <value>
  236. /// <c>true</c> if the connection is alive; otherwise, <c>false</c>.
  237. /// </value>
  238. public bool IsAlive
  239. {
  240. get
  241. {
  242. if (_readyState != WsState.OPEN)
  243. return false;
  244. return Ping();
  245. }
  246. }
  247. /// <summary>
  248. /// Gets a value indicating whether a connection is secure.
  249. /// </summary>
  250. /// <value>
  251. /// <c>true</c> if the connection is secure; otherwise, <c>false</c>.
  252. /// </value>
  253. public bool IsSecure
  254. {
  255. get
  256. {
  257. return _isSecure;
  258. }
  259. }
  260. /// <summary>
  261. /// Gets the subprotocol selected by the server.
  262. /// </summary>
  263. /// <value>
  264. /// A <see cref="string"/> that contains the subprotocol if any. By default, <c>String.Empty</c>.
  265. /// </value>
  266. public string Protocol
  267. {
  268. get
  269. {
  270. return _protocol;
  271. }
  272. }
  273. /// <summary>
  274. /// Gets the state of the connection.
  275. /// </summary>
  276. /// <value>
  277. /// A <see cref="WebSocketSharp.WsState"/>. By default, <c>WsState.CONNECTING</c>.
  278. /// </value>
  279. public WsState ReadyState
  280. {
  281. get
  282. {
  283. return _readyState;
  284. }
  285. }
  286. /// <summary>
  287. /// Gets the untransmitted WebSocket frames.
  288. /// </summary>
  289. /// <value>
  290. /// A <c>IList&lt;WsFrame&gt;</c> that contains the untransmitted WebSocket frames.
  291. /// </value>
  292. public IList<WsFrame> UnTransmittedBuffer
  293. {
  294. get
  295. {
  296. return _unTransmittedBuffer;
  297. }
  298. }
  299. /// <summary>
  300. /// Gets or sets the WebSocket URL.
  301. /// </summary>
  302. /// <value>
  303. /// A <see cref="Uri"/> that contains the WebSocket URL.
  304. /// </value>
  305. public Uri Url
  306. {
  307. get { return _uri; }
  308. set
  309. {
  310. if (_readyState == WsState.CONNECTING && !_isClient)
  311. _uri = value;
  312. }
  313. }
  314. /// <summary>
  315. /// Gets or sets the WebSocket Origin.
  316. /// </summary>
  317. public string Origin
  318. {
  319. get { return this._origin; }
  320. set { this._origin = value; }
  321. }
  322. /// <summary>
  323. /// Gets or sets the extra WebSocket handshake headers.
  324. /// </summary>
  325. public IDictionary<string, string> ExtraHeaders { get; set; }
  326. #endregion
  327. #region Events
  328. /// <summary>
  329. /// Occurs when the WebSocket connection has been established.
  330. /// </summary>
  331. public event EventHandler OnOpen;
  332. /// <summary>
  333. /// Occurs when the WebSocket receives a data frame.
  334. /// </summary>
  335. public event EventHandler<MessageEventArgs> OnMessage;
  336. /// <summary>
  337. /// Occurs when the WebSocket gets an error.
  338. /// </summary>
  339. public event EventHandler<ErrorEventArgs> OnError;
  340. /// <summary>
  341. /// Occurs when the WebSocket receives a Close frame or the Close method is called.
  342. /// </summary>
  343. public event EventHandler<CloseEventArgs> OnClose;
  344. #endregion
  345. #region Private Methods
  346. // As Server
  347. private void acceptHandshake()
  348. {
  349. var req = receiveOpeningHandshake();
  350. string msg;
  351. if (!isValidRequest(req, out msg))
  352. {
  353. onError(msg);
  354. close(CloseStatusCode.HANDSHAKE_FAILURE, msg);
  355. return;
  356. }
  357. sendResponseHandshake();
  358. onOpen();
  359. }
  360. private bool canSendAsCloseFrame(PayloadData data)
  361. {
  362. if (data.Length >= 2)
  363. {
  364. var code = Ext.To<ushort>(Ext.SubArray(data.ToBytes(), 0, 2), ByteOrder.BIG);
  365. if (code == (ushort)CloseStatusCode.NO_STATUS_CODE ||
  366. code == (ushort)CloseStatusCode.ABNORMAL ||
  367. code == (ushort)CloseStatusCode.HANDSHAKE_FAILURE)
  368. return false;
  369. }
  370. return true;
  371. }
  372. private void close(HttpStatusCode code)
  373. {
  374. if (_readyState != WsState.CONNECTING || _isClient)
  375. return;
  376. sendResponseHandshake(code);
  377. closeConnection();
  378. }
  379. private void close(PayloadData data)
  380. {
  381. #if DEBUG
  382. Console.WriteLine("WS: Info@close: Current thread IsBackground ?: {0}", Thread.CurrentThread.IsBackground);
  383. #endif
  384. lock (_forClose)
  385. {
  386. // Whether the closing handshake has been started already ?
  387. if (_readyState == WsState.CLOSING ||
  388. _readyState == WsState.CLOSED)
  389. return;
  390. // Whether the closing handshake as server is started before the connection has been established ?
  391. if (_readyState == WsState.CONNECTING && !_isClient)
  392. {
  393. sendResponseHandshake(HttpStatusCode.BadRequest);
  394. onClose(new CloseEventArgs(data));
  395. return;
  396. }
  397. _readyState = WsState.CLOSING;
  398. }
  399. // Whether a close status code that must not be set for send is used ?
  400. if (!canSendAsCloseFrame(data))
  401. {
  402. onClose(new CloseEventArgs(data));
  403. return;
  404. }
  405. closeHandshake(data);
  406. #if DEBUG
  407. Console.WriteLine("WS: Info@close: Exits close method.");
  408. #endif
  409. }
  410. private void close(CloseStatusCode code, string reason)
  411. {
  412. close((ushort)code, reason);
  413. }
  414. private void close(ushort code, string reason)
  415. {
  416. var data = new List<byte>(Ext.ToBytes(code, ByteOrder.BIG));
  417. if (!Ext.IsNullOrEmpty(reason))
  418. {
  419. var buffer = Encoding.UTF8.GetBytes(reason);
  420. data.AddRange(buffer);
  421. }
  422. var payloadData = new PayloadData(data.ToArray());
  423. if (payloadData.Length > 125)
  424. {
  425. var msg = "A Close frame must have a payload length of 125 bytes or less.";
  426. onError(msg);
  427. return;
  428. }
  429. close(payloadData);
  430. }
  431. private bool closeConnection()
  432. {
  433. _readyState = WsState.CLOSED;
  434. try
  435. {
  436. if (_httpContext != null)
  437. {
  438. _httpContext.Response.Close();
  439. _wsStream = null;
  440. _httpContext = null;
  441. }
  442. if (_wsStream != null)
  443. {
  444. _wsStream.Dispose();
  445. _wsStream = null;
  446. }
  447. if (_tcpClient != null)
  448. {
  449. _tcpClient.Close();
  450. _tcpClient = null;
  451. }
  452. return true;
  453. }
  454. catch (Exception ex)
  455. {
  456. onError(ex.Message);
  457. return false;
  458. }
  459. }
  460. private void closeHandshake(PayloadData data)
  461. {
  462. var args = new CloseEventArgs(data);
  463. var frame = createFrame(Fin.FINAL, Opcode.CLOSE, data);
  464. send(frame);
  465. onClose(args);
  466. }
  467. // As Client
  468. private string createBase64Key()
  469. {
  470. var src = new byte[16];
  471. var rand = new Random();
  472. rand.NextBytes(src);
  473. return Convert.ToBase64String(src);
  474. }
  475. // As Client
  476. private void createClientStream()
  477. {
  478. var host = _uri.DnsSafeHost;
  479. var port = _uri.Port > 0
  480. ? _uri.Port
  481. : _isSecure ? 443 : 80;
  482. _tcpClient = new TcpClient(host, port);
  483. _wsStream = WsStream.CreateClientStream(_tcpClient, host, _isSecure);
  484. }
  485. private WsFrame createFrame(Fin fin, Opcode opcode, PayloadData payloadData)
  486. {
  487. return _isClient
  488. ? new WsFrame(fin, opcode, payloadData)
  489. : new WsFrame(fin, opcode, Mask.UNMASK, payloadData);
  490. }
  491. // As Client
  492. private RequestHandshake createOpeningHandshake()
  493. {
  494. var path = _uri.PathAndQuery;
  495. var host = _uri.DnsSafeHost;
  496. var port = ((System.Net.IPEndPoint)_tcpClient.Client.RemoteEndPoint).Port;
  497. if (port != 80)
  498. host += ":" + port;
  499. var req = new RequestHandshake(path);
  500. req.AddHeader("Host", host);
  501. req.AddHeader("Sec-WebSocket-Key", _base64key);
  502. if (!Ext.IsNullOrEmpty(_protocols))
  503. req.AddHeader("Sec-WebSocket-Protocol", _protocols);
  504. req.AddHeader("Sec-WebSocket-Version", _version);
  505. if (!string.IsNullOrEmpty(this._origin))
  506. req.AddHeader("Origin", this._origin);
  507. //extra headers
  508. if (this.ExtraHeaders != null)
  509. foreach (var i in this.ExtraHeaders)
  510. req.AddHeader(i.Key, i.Value);
  511. return req;
  512. }
  513. // As Server
  514. private ResponseHandshake createResponseHandshake()
  515. {
  516. var res = new ResponseHandshake();
  517. res.AddHeader("Sec-WebSocket-Accept", createResponseKey());
  518. return res;
  519. }
  520. // As Server
  521. private ResponseHandshake createResponseHandshake(HttpStatusCode code)
  522. {
  523. var res = ResponseHandshake.CreateCloseResponse(code);
  524. res.AddHeader("Sec-WebSocket-Version", _version);
  525. return res;
  526. }
  527. private string createResponseKey()
  528. {
  529. SHA1 sha1 = new SHA1CryptoServiceProvider();
  530. var sb = new StringBuilder(_base64key);
  531. sb.Append(_guid);
  532. var src = sha1.ComputeHash(Encoding.UTF8.GetBytes(sb.ToString()));
  533. return Convert.ToBase64String(src);
  534. }
  535. // As Client
  536. private void doHandshake()
  537. {
  538. var res = sendOpeningHandshake();
  539. string msg;
  540. if (!isValidResponse(res, out msg))
  541. {
  542. onError(msg);
  543. close(CloseStatusCode.HANDSHAKE_FAILURE, msg);
  544. return;
  545. }
  546. onOpen();
  547. }
  548. private bool isValidCloseStatusCode(ushort code, out string message)
  549. {
  550. if (code < 1000)
  551. {
  552. message = "Close status codes in the range 0-999 are not used: " + code;
  553. return false;
  554. }
  555. if (code > 4999)
  556. {
  557. message = "Out of reserved close status code range: " + code;
  558. return false;
  559. }
  560. message = String.Empty;
  561. return true;
  562. }
  563. private bool isValidFrame(WsFrame frame)
  564. {
  565. if (frame == null)
  566. {
  567. var msg = "The WebSocket frame can not be read from the network stream.";
  568. close(CloseStatusCode.ABNORMAL, msg);
  569. return false;
  570. }
  571. return true;
  572. }
  573. // As Server
  574. private bool isValidRequest(RequestHandshake request, out string message)
  575. {
  576. if (!request.IsWebSocketRequest)
  577. {
  578. message = "Invalid WebSocket request.";
  579. return false;
  580. }
  581. if (_uri.IsAbsoluteUri && !isValidRequestHost(request.Headers["Host"], out message))
  582. return false;
  583. if (!request.HeaderExists("Sec-WebSocket-Version", _version))
  584. {
  585. message = "Unsupported Sec-WebSocket-Version.";
  586. return false;
  587. }
  588. _base64key = request.Headers["Sec-WebSocket-Key"];
  589. if (request.HeaderExists("Sec-WebSocket-Protocol"))
  590. _protocols = request.Headers["Sec-WebSocket-Protocol"];
  591. if (request.HeaderExists("Sec-WebSocket-Extensions"))
  592. _extensions = request.Headers["Sec-WebSocket-Extensions"];
  593. _queryString = request.QueryString;
  594. message = String.Empty;
  595. return true;
  596. }
  597. // As Server
  598. private bool isValidRequestHost(string value, out string message)
  599. {
  600. var host = _uri.DnsSafeHost;
  601. var type = Uri.CheckHostName(host);
  602. var address = _endPoint.Address;
  603. var port = _endPoint.Port;
  604. var expectedHost1 = host;
  605. var expectedHost2 = type == UriHostNameType.Dns
  606. ? address.ToString()
  607. : System.Net.Dns.GetHostEntry(address).HostName;
  608. if (port != 80)
  609. {
  610. expectedHost1 += ":" + port;
  611. expectedHost2 += ":" + port;
  612. }
  613. if (Ext.NotEqual(expectedHost1, value, false) &&
  614. Ext.NotEqual(expectedHost2, value, false))
  615. {
  616. message = "Invalid Host.";
  617. return false;
  618. }
  619. message = String.Empty;
  620. return true;
  621. }
  622. // As Client
  623. private bool isValidResponse(ResponseHandshake response, out string message)
  624. {
  625. if (!response.IsWebSocketResponse)
  626. {
  627. message = "Invalid WebSocket response.";
  628. return false;
  629. }
  630. if (!response.HeaderExists("Sec-WebSocket-Accept", createResponseKey()))
  631. {
  632. message = "Invalid Sec-WebSocket-Accept.";
  633. return false;
  634. }
  635. if (response.HeaderExists("Sec-WebSocket-Version") &&
  636. !response.HeaderExists("Sec-WebSocket-Version", _version))
  637. {
  638. message = "Unsupported Sec-WebSocket-Version.";
  639. return false;
  640. }
  641. if (response.HeaderExists("Sec-WebSocket-Protocol"))
  642. _protocol = response.Headers["Sec-WebSocket-Protocol"];
  643. if (response.HeaderExists("Sec-WebSocket-Extensions"))
  644. _extensions = response.Headers["Sec-WebSocket-Extensions"];
  645. message = String.Empty;
  646. return true;
  647. }
  648. private void onClose(CloseEventArgs eventArgs)
  649. {
  650. if (!Thread.CurrentThread.IsBackground)
  651. if (_exitMessageLoop != null)
  652. _exitMessageLoop.WaitOne(5 * 1000, false);
  653. if (closeConnection())
  654. eventArgs.WasClean = true;
  655. Ext.Emit(OnClose, this, eventArgs);
  656. }
  657. private void onError(string message)
  658. {
  659. #if DEBUG
  660. var callerFrame = new StackFrame(1);
  661. var caller = callerFrame.GetMethod();
  662. Console.WriteLine("WS: Error@{0}: {1}", caller.Name, message);
  663. #endif
  664. Ext.Emit(OnError, this, new ErrorEventArgs(message));
  665. }
  666. private void onMessage(MessageEventArgs eventArgs)
  667. {
  668. if (eventArgs != null)
  669. Ext.Emit(OnMessage, this, eventArgs);
  670. }
  671. private void onOpen()
  672. {
  673. _readyState = WsState.OPEN;
  674. startMessageLoop();
  675. Ext.Emit(OnOpen, this, EventArgs.Empty);
  676. }
  677. private bool ping(string message, int millisecondsTimeout)
  678. {
  679. var buffer = Encoding.UTF8.GetBytes(message);
  680. if (buffer.Length > 125)
  681. {
  682. var msg = "A Ping frame must have a payload length of 125 bytes or less.";
  683. onError(msg);
  684. return false;
  685. }
  686. if (!send(Fin.FINAL, Opcode.PING, buffer))
  687. return false;
  688. return _receivePong.WaitOne(millisecondsTimeout, false);
  689. }
  690. private void pong(PayloadData data)
  691. {
  692. var frame = createFrame(Fin.FINAL, Opcode.PONG, data);
  693. send(frame);
  694. }
  695. private void pong(string data)
  696. {
  697. var payloadData = new PayloadData(data);
  698. pong(payloadData);
  699. }
  700. private WsFrame readFrame()
  701. {
  702. var frame = _wsStream.ReadFrame();
  703. return isValidFrame(frame) ? frame : null;
  704. }
  705. private string[] readHandshake()
  706. {
  707. return _wsStream.ReadHandshake();
  708. }
  709. private MessageEventArgs receive(WsFrame frame)
  710. {
  711. if (!isValidFrame(frame))
  712. return null;
  713. if ((frame.Fin == Fin.FINAL && frame.Opcode == Opcode.CONT) ||
  714. (frame.Fin == Fin.MORE && frame.Opcode == Opcode.CONT))
  715. return null;
  716. if (frame.Fin == Fin.MORE)
  717. {// MORE
  718. var merged = receiveFragmented(frame);
  719. return merged != null
  720. ? new MessageEventArgs(frame.Opcode, new PayloadData(merged))
  721. : null;
  722. }
  723. if (frame.Opcode == Opcode.CLOSE)
  724. {// FINAL & CLOSE
  725. #if DEBUG
  726. Console.WriteLine("WS: Info@receive: Starts closing handshake.");
  727. #endif
  728. close(frame.PayloadData);
  729. return null;
  730. }
  731. if (frame.Opcode == Opcode.PING)
  732. {// FINAL & PING
  733. #if DEBUG
  734. Console.WriteLine("WS: Info@receive: Returns Pong.");
  735. #endif
  736. pong(frame.PayloadData);
  737. return null;
  738. }
  739. if (frame.Opcode == Opcode.PONG)
  740. {// FINAL & PONG
  741. #if DEBUG
  742. Console.WriteLine("WS: Info@receive: Receives Pong.");
  743. #endif
  744. _receivePong.Set();
  745. return null;
  746. }
  747. // FINAL & (TEXT | BINARY)
  748. return new MessageEventArgs(frame.Opcode, frame.PayloadData);
  749. }
  750. private byte[] receiveFragmented(WsFrame firstFrame)
  751. {
  752. var buffer = new List<byte>(firstFrame.PayloadData.ToBytes());
  753. while (true)
  754. {
  755. var frame = readFrame();
  756. if (frame == null)
  757. return null;
  758. if (frame.Fin == Fin.MORE)
  759. {
  760. if (frame.Opcode == Opcode.CONT)
  761. {// MORE & CONT
  762. buffer.AddRange(frame.PayloadData.ToBytes());
  763. continue;
  764. }
  765. #if DEBUG
  766. Console.WriteLine("WS: Info@receiveFragmented: Starts closing handshake.");
  767. #endif
  768. close(CloseStatusCode.INCORRECT_DATA, String.Empty);
  769. return null;
  770. }
  771. if (frame.Opcode == Opcode.CONT)
  772. {// FINAL & CONT
  773. buffer.AddRange(frame.PayloadData.ToBytes());
  774. break;
  775. }
  776. if (frame.Opcode == Opcode.CLOSE)
  777. {// FINAL & CLOSE
  778. #if DEBUG
  779. Console.WriteLine("WS: Info@receiveFragmented: Starts closing handshake.");
  780. #endif
  781. close(frame.PayloadData);
  782. return null;
  783. }
  784. if (frame.Opcode == Opcode.PING)
  785. {// FINAL & PING
  786. #if DEBUG
  787. Console.WriteLine("WS: Info@receiveFragmented: Returns Pong.");
  788. #endif
  789. pong(frame.PayloadData);
  790. continue;
  791. }
  792. if (frame.Opcode == Opcode.PONG)
  793. {// FINAL & PONG
  794. #if DEBUG
  795. Console.WriteLine("WS: Info@receiveFragmented: Receives Pong.");
  796. #endif
  797. _receivePong.Set();
  798. continue;
  799. }
  800. // FINAL & (TEXT | BINARY)
  801. #if DEBUG
  802. Console.WriteLine("WS: Info@receiveFragmented: Starts closing handshake.");
  803. #endif
  804. close(CloseStatusCode.INCORRECT_DATA, String.Empty);
  805. return null;
  806. }
  807. return buffer.ToArray();
  808. }
  809. // As Server
  810. private RequestHandshake receiveOpeningHandshake()
  811. {
  812. var req = RequestHandshake.Parse(_context);
  813. #if DEBUG
  814. Console.WriteLine("WS: Info@receiveOpeningHandshake: Opening handshake from client:\n");
  815. Console.WriteLine(req.ToString());
  816. #endif
  817. return req;
  818. }
  819. // As Client
  820. private ResponseHandshake receiveResponseHandshake()
  821. {
  822. var res = ResponseHandshake.Parse(readHandshake());
  823. #if DEBUG
  824. Console.WriteLine("WS: Info@receiveResponseHandshake: Response handshake from server:\n");
  825. Console.WriteLine(res.ToString());
  826. #endif
  827. return res;
  828. }
  829. private bool send(WsFrame frame)
  830. {
  831. if (_readyState == WsState.CONNECTING ||
  832. _readyState == WsState.CLOSED)
  833. {
  834. var msg = "The WebSocket connection isn't established or has been closed.";
  835. onError(msg);
  836. return false;
  837. }
  838. try
  839. {
  840. if (_unTransmittedBuffer.Count == 0)
  841. {
  842. if (_wsStream != null)
  843. {
  844. _wsStream.WriteFrame(frame);
  845. return true;
  846. }
  847. }
  848. if (_unTransmittedBuffer.Count > 0)
  849. {
  850. _unTransmittedBuffer.Add(frame);
  851. var msg = "Current data can not be sent because there is untransmitted data.";
  852. onError(msg);
  853. }
  854. return false;
  855. }
  856. catch (Exception ex)
  857. {
  858. _unTransmittedBuffer.Add(frame);
  859. onError(ex.Message);
  860. return false;
  861. }
  862. }
  863. private void send(Opcode opcode, byte[] data)
  864. {
  865. using (MemoryStream ms = new MemoryStream(data))
  866. {
  867. send(opcode, ms);
  868. }
  869. }
  870. private void send(Opcode opcode, Stream stream)
  871. {
  872. lock (_forSend)
  873. {
  874. try
  875. {
  876. if (_readyState != WsState.OPEN)
  877. {
  878. var msg = "The WebSocket connection isn't established or has been closed.";
  879. onError(msg);
  880. return;
  881. }
  882. var length = stream.Length;
  883. if (length <= _fragmentLen)
  884. send(Fin.FINAL, opcode, Ext.ReadBytes(stream, (int)length));
  885. else
  886. sendFragmented(opcode, stream);
  887. }
  888. catch (Exception ex)
  889. {
  890. onError(ex.Message);
  891. }
  892. }
  893. }
  894. private bool send(Fin fin, Opcode opcode, byte[] data)
  895. {
  896. var frame = createFrame(fin, opcode, new PayloadData(data));
  897. return send(frame);
  898. }
  899. private void sendAsync(Opcode opcode, byte[] data, Action completed)
  900. {
  901. sendAsync(opcode, new MemoryStream(data), completed);
  902. }
  903. private void sendAsync(Opcode opcode, Stream stream, Action completed)
  904. {
  905. Action<Opcode, Stream> action = send;
  906. AsyncCallback callback = (ar) =>
  907. {
  908. try
  909. {
  910. action.EndInvoke(ar);
  911. if (completed != null)
  912. completed();
  913. }
  914. catch (Exception ex)
  915. {
  916. onError(ex.Message);
  917. }
  918. finally
  919. {
  920. stream.Close();
  921. }
  922. };
  923. action.BeginInvoke(opcode, stream, callback, null);
  924. }
  925. private long sendFragmented(Opcode opcode, Stream stream)
  926. {
  927. var length = stream.Length;
  928. var quo = length / _fragmentLen;
  929. var rem = length % _fragmentLen;
  930. var count = rem == 0 ? quo - 2 : quo - 1;
  931. // First
  932. var buffer = new byte[_fragmentLen];
  933. long readLen = stream.Read(buffer, 0, _fragmentLen);
  934. send(Fin.MORE, opcode, buffer);
  935. // Mid
  936. Ext.Times(count, () =>
  937. {
  938. readLen += stream.Read(buffer, 0, _fragmentLen);
  939. send(Fin.MORE, Opcode.CONT, buffer);
  940. });
  941. // Final
  942. if (rem != 0)
  943. buffer = new byte[rem];
  944. readLen += stream.Read(buffer, 0, buffer.Length);
  945. send(Fin.FINAL, Opcode.CONT, buffer);
  946. return readLen;
  947. }
  948. // As Client
  949. private ResponseHandshake sendOpeningHandshake()
  950. {
  951. var req = createOpeningHandshake();
  952. sendOpeningHandshake(req);
  953. return receiveResponseHandshake();
  954. }
  955. // As Client
  956. private void sendOpeningHandshake(RequestHandshake request)
  957. {
  958. #if DEBUG
  959. Console.WriteLine("WS: Info@sendOpeningHandshake: Opening handshake from client:\n");
  960. Console.WriteLine(request.ToString());
  961. #endif
  962. writeHandshake(request);
  963. }
  964. // As Server
  965. private void sendResponseHandshake()
  966. {
  967. var res = createResponseHandshake();
  968. sendResponseHandshake(res);
  969. }
  970. // As Server
  971. private void sendResponseHandshake(HttpStatusCode code)
  972. {
  973. var res = createResponseHandshake(code);
  974. sendResponseHandshake(res);
  975. }
  976. /// <summary>
  977. /// @Author: HTL
  978. /// @Email: Huangyuan413026@163.com
  979. /// @DateTime: 2015-06-03 19:54:49
  980. /// @Description: 获取当前堆栈的上级调用方法列表,直到最终调用者,只会返回调用的各方法,而不会返回具体的出错行数,可参考:微软真是个十足的混蛋啊!让我们跟踪Exception到行把!(不明真相群众请入)
  981. /// </summary>
  982. /// <returns></returns>
  983. static string GetStackTraceModelName()
  984. {
  985. //当前堆栈信息
  986. System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace();
  987. System.Diagnostics.StackFrame[] sfs = st.GetFrames();
  988. //过虑的方法名称,以下方法将不会出现在返回的方法调用列表中
  989. string _filterdName = "ResponseWrite,ResponseWriteError,";
  990. string _fullName = string.Empty, _methodName = string.Empty;
  991. for (int i = 1; i < sfs.Length; ++i)
  992. {
  993. //非用户代码,系统方法及后面的都是系统调用,不获取用户代码调用结束
  994. if (System.Diagnostics.StackFrame.OFFSET_UNKNOWN == sfs[i].GetILOffset()) break;
  995. _methodName = sfs[i].GetMethod().Name;//方法名称
  996. //sfs[i].GetFileLineNumber();//没有PDB文件的情况下将始终返回0
  997. if (_filterdName.Contains(_methodName)) continue;
  998. _fullName = _methodName + "()->" + _fullName;
  999. }
  1000. st = null;
  1001. sfs = null;
  1002. _filterdName = _methodName = null;
  1003. return _fullName.TrimEnd('-','>');
  1004. }
  1005. // As Server
  1006. private void sendResponseHandshake(ResponseHandshake response)
  1007. {
  1008. #if DEBUG
  1009. Console.WriteLine("WS: Info@sendResponseHandshake: Response handshake from server:\n");
  1010. Console.WriteLine(response.ToString());
  1011. #endif
  1012. writeHandshake(response);
  1013. }
  1014. private int count = 0;
  1015. // 0 可读, 1 读取中 , 2 断开
  1016. private volatile int lockI = 0;
  1017. private Thread refreshThread;
  1018. private void startMessageLoop()
  1019. {
  1020. _exitMessageLoop = new AutoResetEvent(false);
  1021. _receivePong = new AutoResetEvent(false);
  1022. Action<WsFrame> completed = frame =>
  1023. {
  1024. try
  1025. {
  1026. onMessage(receive(frame));
  1027. if (_readyState == WsState.OPEN)
  1028. {
  1029. lockI = 0;
  1030. count++;
  1031. // Console.WriteLine("stack in " + count + " " + GetStackTraceModelName());
  1032. }
  1033. else
  1034. {
  1035. lockI = 2;
  1036. _exitMessageLoop.Set();
  1037. // Console.WriteLine("stack over depth " + count);
  1038. count = 0;
  1039. }
  1040. }
  1041. catch (WsReceivedTooBigMessageException ex)
  1042. {
  1043. close(CloseStatusCode.TOO_BIG, ex.Message);
  1044. count = 0;
  1045. lockI = 2;
  1046. }
  1047. catch (Exception ex)
  1048. {
  1049. count = 0;
  1050. //HACK:close with 1006 when onMessage exception?
  1051. close(CloseStatusCode.ABNORMAL
  1052. , string.Format("An exception has occured: {0}", ex.Message));
  1053. lockI = 2;
  1054. }
  1055. };
  1056. // 0 可读, 1 读取中 , 2 断开
  1057. refreshThread = new Thread(o =>
  1058. {
  1059. while (lockI != 2 && _readyState == WsState.OPEN)
  1060. {
  1061. if (lockI == 1)
  1062. {
  1063. Thread.Sleep(new TimeSpan(0, 0, 0, 0, 1));
  1064. }
  1065. else if (lockI == 0)
  1066. {
  1067. lockI = 1;
  1068. _wsStream.ReadFrameAsync(completed);
  1069. }
  1070. }
  1071. });
  1072. refreshThread.IsBackground = true;
  1073. refreshThread.Name = "StartMessageLoop thread";
  1074. refreshThread.Start();
  1075. }
  1076. private bool tryCreateUri(string uriString, out Uri result, out string message)
  1077. {
  1078. return Ext.TryCreateWebSocketUri(uriString, out result, out message);
  1079. }
  1080. private void writeHandshake(Handshake handshake)
  1081. {
  1082. _wsStream.WriteHandshake(handshake);
  1083. }
  1084. #endregion
  1085. #region Internal Method
  1086. // As Server
  1087. internal void Close(HttpStatusCode code)
  1088. {
  1089. close(code);
  1090. }
  1091. #endregion
  1092. #region Public Methods
  1093. /// <summary>
  1094. /// Closes the connection and releases all associated resources after sends a Close control frame.
  1095. /// </summary>
  1096. public void Close()
  1097. {
  1098. var data = new PayloadData(new byte[] { });
  1099. close(data);
  1100. }
  1101. /// <summary>
  1102. /// Closes the connection and releases all associated resources after sends a Close control frame.
  1103. /// </summary>
  1104. /// <param name="code">
  1105. /// A <see cref="WebSocketSharp.Frame.CloseStatusCode"/> that contains a status code indicating a reason for closure.
  1106. /// </param>
  1107. public void Close(CloseStatusCode code)
  1108. {
  1109. Close(code, String.Empty);
  1110. }
  1111. /// <summary>
  1112. /// Closes the connection and releases all associated resources after sends a Close control frame.
  1113. /// </summary>
  1114. /// <param name="code">
  1115. /// A <see cref="ushort"/> that contains a status code indicating a reason for closure.
  1116. /// </param>
  1117. public void Close(ushort code)
  1118. {
  1119. Close(code, String.Empty);
  1120. }
  1121. /// <summary>
  1122. /// Closes the connection and releases all associated resources after sends a Close control frame.
  1123. /// </summary>
  1124. /// <param name="code">
  1125. /// A <see cref="WebSocketSharp.Frame.CloseStatusCode"/> that contains a status code indicating a reason for closure.
  1126. /// </param>
  1127. /// <param name="reason">
  1128. /// A <see cref="string"/> that contains a reason for closure.
  1129. /// </param>
  1130. public void Close(CloseStatusCode code, string reason)
  1131. {
  1132. Close((ushort)code, reason);
  1133. }
  1134. /// <summary>
  1135. /// Closes the connection and releases all associated resources after sends a Close control frame.
  1136. /// </summary>
  1137. /// <param name="code">
  1138. /// A <see cref="ushort"/> that contains a status code indicating a reason for closure.
  1139. /// </param>
  1140. /// <param name="reason">
  1141. /// A <see cref="string"/> that contains a reason for closure.
  1142. /// </param>
  1143. public void Close(ushort code, string reason)
  1144. {
  1145. string msg;
  1146. if (!isValidCloseStatusCode(code, out msg))
  1147. {
  1148. onError(msg);
  1149. return;
  1150. }
  1151. close(code, reason);
  1152. }
  1153. /// <summary>
  1154. /// Establishes a connection.
  1155. /// </summary>
  1156. public void Connect()
  1157. {
  1158. if (_readyState == WsState.OPEN)
  1159. {
  1160. Console.WriteLine("WS: Info@Connect: The WebSocket connection has been established already.");
  1161. return;
  1162. }
  1163. try
  1164. {
  1165. // As client
  1166. if (_isClient)
  1167. {
  1168. createClientStream();
  1169. doHandshake();
  1170. return;
  1171. }
  1172. // As server
  1173. acceptHandshake();
  1174. }
  1175. catch (Exception ex)
  1176. {
  1177. onError(ex.Message);
  1178. close(CloseStatusCode.HANDSHAKE_FAILURE, "An exception has occured.");
  1179. }
  1180. }
  1181. /// <summary>
  1182. /// Closes the connection and releases all associated resources after sends a Close control frame.
  1183. /// </summary>
  1184. /// <remarks>
  1185. /// Call <see cref="Dispose"/> when you are finished using the <see cref="WebSocketSharp.WebSocket"/>. The
  1186. /// <see cref="Dispose"/> method leaves the <see cref="WebSocketSharp.WebSocket"/> in an unusable state. After
  1187. /// calling <see cref="Dispose"/>, you must release all references to the <see cref="WebSocketSharp.WebSocket"/> so
  1188. /// the garbage collector can reclaim the memory that the <see cref="WebSocketSharp.WebSocket"/> was occupying.
  1189. /// </remarks>
  1190. public void Dispose()
  1191. {
  1192. Close(CloseStatusCode.AWAY);
  1193. }
  1194. /// <summary>
  1195. /// Sends a Ping frame using the connection.
  1196. /// </summary>
  1197. /// <returns>
  1198. /// <c>true</c> if the WebSocket receives a Pong frame in a time; otherwise, <c>false</c>.
  1199. /// </returns>
  1200. public bool Ping()
  1201. {
  1202. return Ping(String.Empty);
  1203. }
  1204. /// <summary>
  1205. /// Sends a Ping frame with a message using the connection.
  1206. /// </summary>
  1207. /// <param name="message">
  1208. /// A <see cref="string"/> that contains the message to be sent.
  1209. /// </param>
  1210. /// <returns>
  1211. /// <c>true</c> if the WebSocket receives a Pong frame in a time; otherwise, <c>false</c>.
  1212. /// </returns>
  1213. public bool Ping(string message)
  1214. {
  1215. if (message == null)
  1216. message = String.Empty;
  1217. return _isClient
  1218. ? ping(message, 5 * 1000)
  1219. : ping(message, 1 * 1000);
  1220. }
  1221. /// <summary>
  1222. /// Sends a text data using the connection.
  1223. /// </summary>
  1224. /// <param name="data">
  1225. /// A <see cref="string"/> that contains the text data to be sent.
  1226. /// </param>
  1227. public void Send(string data)
  1228. {
  1229. if (data == null)
  1230. {
  1231. onError("'data' must not be null.");
  1232. return;
  1233. }
  1234. var buffer = Encoding.UTF8.GetBytes(data);
  1235. send(Opcode.TEXT, buffer);
  1236. }
  1237. /// <summary>
  1238. /// Sends a binary data using the connection.
  1239. /// </summary>
  1240. /// <param name="data">
  1241. /// An array of <see cref="byte"/> that contains the binary data to be sent.
  1242. /// </param>
  1243. public void Send(byte[] data)
  1244. {
  1245. if (data == null)
  1246. {
  1247. onError("'data' must not be null.");
  1248. return;
  1249. }
  1250. send(Opcode.BINARY, data);
  1251. }
  1252. /// <summary>
  1253. /// Sends a binary data using the connection.
  1254. /// </summary>
  1255. /// <param name="file">
  1256. /// A <see cref="FileInfo"/> that contains the binary data to be sent.
  1257. /// </param>
  1258. public void Send(FileInfo file)
  1259. {
  1260. if (file == null)
  1261. {
  1262. onError("'file' must not be null.");
  1263. return;
  1264. }
  1265. using (FileStream fs = file.OpenRead())
  1266. {
  1267. send(Opcode.BINARY, fs);
  1268. }
  1269. }
  1270. /// <summary>
  1271. /// Sends a text data asynchronously using the connection.
  1272. /// </summary>
  1273. /// <param name="data">
  1274. /// A <see cref="string"/> that contains the text data to be sent.
  1275. /// </param>
  1276. /// <param name="completed">
  1277. /// An <see cref="Action"/> delegate that contains the method(s) that is called when an asynchronous operation completes.
  1278. /// </param>
  1279. public void SendAsync(string data, Action completed)
  1280. {
  1281. if (data == null)
  1282. {
  1283. onError("'data' must not be null.");
  1284. return;
  1285. }
  1286. var buffer = Encoding.UTF8.GetBytes(data);
  1287. sendAsync(Opcode.TEXT, buffer, completed);
  1288. }
  1289. /// <summary>
  1290. /// Sends a binary data asynchronously using the connection.
  1291. /// </summary>
  1292. /// <param name="data">
  1293. /// An array of <see cref="byte"/> that contains the binary data to be sent.
  1294. /// </param>
  1295. /// <param name="completed">
  1296. /// An <see cref="Action"/> delegate that contains the method(s) that is called when an asynchronous operation completes.
  1297. /// </param>
  1298. public void SendAsync(byte[] data, Action completed)
  1299. {
  1300. if (data == null)
  1301. {
  1302. onError("'data' must not be null.");
  1303. return;
  1304. }
  1305. sendAsync(Opcode.BINARY, data, completed);
  1306. }
  1307. /// <summary>
  1308. /// Sends a binary data asynchronously using the connection.
  1309. /// </summary>
  1310. /// <param name="file">
  1311. /// A <see cref="FileInfo"/> that contains the binary data to be sent.
  1312. /// </param>
  1313. /// <param name="completed">
  1314. /// An <see cref="Action"/> delegate that contains the method(s) that is called when an asynchronous operation completes.
  1315. /// </param>
  1316. public void SendAsync(FileInfo file, Action completed)
  1317. {
  1318. if (file == null)
  1319. {
  1320. onError("'file' must not be null.");
  1321. return;
  1322. }
  1323. sendAsync(Opcode.BINARY, file.OpenRead(), completed);
  1324. }
  1325. #endregion
  1326. }
  1327. }