WebSocketSessionManager.cs 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621
  1. #region License
  2. /*
  3. * WebSocketSessionManager.cs
  4. *
  5. * The MIT License
  6. *
  7. * Copyright (c) 2012-2023 sta.blockhead
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. */
  27. #endregion
  28. using System;
  29. using System.Collections;
  30. using System.Collections.Generic;
  31. using System.IO;
  32. using System.Linq;
  33. using System.Text;
  34. using System.Threading;
  35. using System.Timers;
  36. namespace WebSocketSharp.Server
  37. {
  38. /// <summary>
  39. /// Provides the management function for the sessions in a WebSocket service.
  40. /// </summary>
  41. /// <remarks>
  42. /// This class manages the sessions in a WebSocket service provided by the
  43. /// <see cref="WebSocketServer"/> or <see cref="HttpServer"/> class.
  44. /// </remarks>
  45. public class WebSocketSessionManager
  46. {
  47. #region Private Fields
  48. private object _forSweep;
  49. private volatile bool _keepClean;
  50. private Logger _log;
  51. private static readonly byte[] _rawEmptyPingFrame;
  52. private Dictionary<string, IWebSocketSession> _sessions;
  53. private volatile ServerState _state;
  54. private volatile bool _sweeping;
  55. private System.Timers.Timer _sweepTimer;
  56. private object _sync;
  57. private TimeSpan _waitTime;
  58. #endregion
  59. #region Static Constructor
  60. static WebSocketSessionManager ()
  61. {
  62. _rawEmptyPingFrame = WebSocketFrame.CreatePingFrame (false).ToArray ();
  63. }
  64. #endregion
  65. #region Internal Constructors
  66. internal WebSocketSessionManager (Logger log)
  67. {
  68. _log = log;
  69. _forSweep = new object ();
  70. _keepClean = true;
  71. _sessions = new Dictionary<string, IWebSocketSession> ();
  72. _state = ServerState.Ready;
  73. _sync = ((ICollection) _sessions).SyncRoot;
  74. _waitTime = TimeSpan.FromSeconds (1);
  75. setSweepTimer (60000);
  76. }
  77. #endregion
  78. #region Internal Properties
  79. internal ServerState State {
  80. get {
  81. return _state;
  82. }
  83. }
  84. #endregion
  85. #region Public Properties
  86. /// <summary>
  87. /// Gets the IDs for the active sessions in the WebSocket service.
  88. /// </summary>
  89. /// <value>
  90. /// <para>
  91. /// An <c>IEnumerable&lt;string&gt;</c> instance.
  92. /// </para>
  93. /// <para>
  94. /// It provides an enumerator which supports the iteration over
  95. /// the collection of the IDs for the active sessions.
  96. /// </para>
  97. /// </value>
  98. public IEnumerable<string> ActiveIDs {
  99. get {
  100. foreach (var res in broadping (_rawEmptyPingFrame)) {
  101. if (res.Value)
  102. yield return res.Key;
  103. }
  104. }
  105. }
  106. /// <summary>
  107. /// Gets the number of the sessions in the WebSocket service.
  108. /// </summary>
  109. /// <value>
  110. /// An <see cref="int"/> that represents the number of the sessions.
  111. /// </value>
  112. public int Count {
  113. get {
  114. lock (_sync)
  115. return _sessions.Count;
  116. }
  117. }
  118. /// <summary>
  119. /// Gets the IDs for the sessions in the WebSocket service.
  120. /// </summary>
  121. /// <value>
  122. /// <para>
  123. /// An <c>IEnumerable&lt;string&gt;</c> instance.
  124. /// </para>
  125. /// <para>
  126. /// It provides an enumerator which supports the iteration over
  127. /// the collection of the IDs for the sessions.
  128. /// </para>
  129. /// </value>
  130. public IEnumerable<string> IDs {
  131. get {
  132. if (_state != ServerState.Start)
  133. return Enumerable.Empty<string> ();
  134. lock (_sync) {
  135. if (_state != ServerState.Start)
  136. return Enumerable.Empty<string> ();
  137. return _sessions.Keys.ToList ();
  138. }
  139. }
  140. }
  141. /// <summary>
  142. /// Gets the IDs for the inactive sessions in the WebSocket service.
  143. /// </summary>
  144. /// <value>
  145. /// <para>
  146. /// An <c>IEnumerable&lt;string&gt;</c> instance.
  147. /// </para>
  148. /// <para>
  149. /// It provides an enumerator which supports the iteration over
  150. /// the collection of the IDs for the inactive sessions.
  151. /// </para>
  152. /// </value>
  153. public IEnumerable<string> InactiveIDs {
  154. get {
  155. foreach (var res in broadping (_rawEmptyPingFrame)) {
  156. if (!res.Value)
  157. yield return res.Key;
  158. }
  159. }
  160. }
  161. /// <summary>
  162. /// Gets the session instance with the specified ID.
  163. /// </summary>
  164. /// <value>
  165. /// <para>
  166. /// A <see cref="IWebSocketSession"/> instance or <see langword="null"/>
  167. /// if not found.
  168. /// </para>
  169. /// <para>
  170. /// The session instance provides the function to access the information
  171. /// in the session.
  172. /// </para>
  173. /// </value>
  174. /// <param name="id">
  175. /// A <see cref="string"/> that specifies the ID of the session to find.
  176. /// </param>
  177. /// <exception cref="ArgumentNullException">
  178. /// <paramref name="id"/> is <see langword="null"/>.
  179. /// </exception>
  180. /// <exception cref="ArgumentException">
  181. /// <paramref name="id"/> is an empty string.
  182. /// </exception>
  183. public IWebSocketSession this[string id] {
  184. get {
  185. if (id == null)
  186. throw new ArgumentNullException ("id");
  187. if (id.Length == 0)
  188. throw new ArgumentException ("An empty string.", "id");
  189. IWebSocketSession session;
  190. tryGetSession (id, out session);
  191. return session;
  192. }
  193. }
  194. /// <summary>
  195. /// Gets or sets a value indicating whether the inactive sessions in
  196. /// the WebSocket service are cleaned up periodically.
  197. /// </summary>
  198. /// <remarks>
  199. /// The set operation works if the current state of the service is
  200. /// Ready or Stop.
  201. /// </remarks>
  202. /// <value>
  203. /// <c>true</c> if the inactive sessions are cleaned up every 60 seconds;
  204. /// otherwise, <c>false</c>.
  205. /// </value>
  206. public bool KeepClean {
  207. get {
  208. return _keepClean;
  209. }
  210. set {
  211. lock (_sync) {
  212. if (!canSet ())
  213. return;
  214. _keepClean = value;
  215. }
  216. }
  217. }
  218. /// <summary>
  219. /// Gets the session instances in the WebSocket service.
  220. /// </summary>
  221. /// <value>
  222. /// <para>
  223. /// An <c>IEnumerable&lt;IWebSocketSession&gt;</c> instance.
  224. /// </para>
  225. /// <para>
  226. /// It provides an enumerator which supports the iteration over
  227. /// the collection of the session instances.
  228. /// </para>
  229. /// </value>
  230. public IEnumerable<IWebSocketSession> Sessions {
  231. get {
  232. if (_state != ServerState.Start)
  233. return Enumerable.Empty<IWebSocketSession> ();
  234. lock (_sync) {
  235. if (_state != ServerState.Start)
  236. return Enumerable.Empty<IWebSocketSession> ();
  237. return _sessions.Values.ToList ();
  238. }
  239. }
  240. }
  241. /// <summary>
  242. /// Gets or sets the time to wait for the response to the WebSocket
  243. /// Ping or Close.
  244. /// </summary>
  245. /// <remarks>
  246. /// The set operation works if the current state of the service is
  247. /// Ready or Stop.
  248. /// </remarks>
  249. /// <value>
  250. /// A <see cref="TimeSpan"/> that represents the time to wait for
  251. /// the response.
  252. /// </value>
  253. /// <exception cref="ArgumentOutOfRangeException">
  254. /// The value specified for a set operation is zero or less.
  255. /// </exception>
  256. public TimeSpan WaitTime {
  257. get {
  258. return _waitTime;
  259. }
  260. set {
  261. if (value <= TimeSpan.Zero) {
  262. var msg = "Zero or less.";
  263. throw new ArgumentOutOfRangeException ("value", msg);
  264. }
  265. lock (_sync) {
  266. if (!canSet ())
  267. return;
  268. _waitTime = value;
  269. }
  270. }
  271. }
  272. #endregion
  273. #region Private Methods
  274. private void broadcast (Opcode opcode, byte[] data, Action completed)
  275. {
  276. var cache = new Dictionary<CompressionMethod, byte[]> ();
  277. try {
  278. foreach (var session in Sessions) {
  279. if (_state != ServerState.Start) {
  280. _log.Error ("The send is cancelled.");
  281. break;
  282. }
  283. session.WebSocket.Send (opcode, data, cache);
  284. }
  285. if (completed != null)
  286. completed ();
  287. }
  288. catch (Exception ex) {
  289. _log.Error (ex.Message);
  290. _log.Debug (ex.ToString ());
  291. }
  292. finally {
  293. cache.Clear ();
  294. }
  295. }
  296. private void broadcast (
  297. Opcode opcode, Stream sourceStream, Action completed
  298. )
  299. {
  300. var cache = new Dictionary <CompressionMethod, Stream> ();
  301. try {
  302. foreach (var session in Sessions) {
  303. if (_state != ServerState.Start) {
  304. _log.Error ("The send is cancelled.");
  305. break;
  306. }
  307. session.WebSocket.Send (opcode, sourceStream, cache);
  308. }
  309. if (completed != null)
  310. completed ();
  311. }
  312. catch (Exception ex) {
  313. _log.Error (ex.Message);
  314. _log.Debug (ex.ToString ());
  315. }
  316. finally {
  317. foreach (var cached in cache.Values)
  318. cached.Dispose ();
  319. cache.Clear ();
  320. }
  321. }
  322. private void broadcastAsync (Opcode opcode, byte[] data, Action completed)
  323. {
  324. ThreadPool.QueueUserWorkItem (
  325. state => broadcast (opcode, data, completed)
  326. );
  327. }
  328. private void broadcastAsync (
  329. Opcode opcode, Stream sourceStream, Action completed
  330. )
  331. {
  332. ThreadPool.QueueUserWorkItem (
  333. state => broadcast (opcode, sourceStream, completed)
  334. );
  335. }
  336. private Dictionary<string, bool> broadping (byte[] rawFrame)
  337. {
  338. var ret = new Dictionary<string, bool> ();
  339. foreach (var session in Sessions) {
  340. if (_state != ServerState.Start) {
  341. ret.Clear ();
  342. break;
  343. }
  344. var res = session.WebSocket.Ping (rawFrame);
  345. ret.Add (session.ID, res);
  346. }
  347. return ret;
  348. }
  349. private bool canSet ()
  350. {
  351. return _state == ServerState.Ready || _state == ServerState.Stop;
  352. }
  353. private static string createID ()
  354. {
  355. return Guid.NewGuid ().ToString ("N");
  356. }
  357. private void setSweepTimer (double interval)
  358. {
  359. _sweepTimer = new System.Timers.Timer (interval);
  360. _sweepTimer.Elapsed += (sender, e) => Sweep ();
  361. }
  362. private void stop (PayloadData payloadData, bool send)
  363. {
  364. var rawFrame = send
  365. ? WebSocketFrame
  366. .CreateCloseFrame (payloadData, false)
  367. .ToArray ()
  368. : null;
  369. lock (_sync) {
  370. _state = ServerState.ShuttingDown;
  371. _sweepTimer.Enabled = false;
  372. foreach (var session in _sessions.Values.ToList ())
  373. session.WebSocket.Close (payloadData, rawFrame);
  374. _state = ServerState.Stop;
  375. }
  376. }
  377. private bool tryGetSession (string id, out IWebSocketSession session)
  378. {
  379. session = null;
  380. if (_state != ServerState.Start)
  381. return false;
  382. lock (_sync) {
  383. if (_state != ServerState.Start)
  384. return false;
  385. return _sessions.TryGetValue (id, out session);
  386. }
  387. }
  388. #endregion
  389. #region Internal Methods
  390. internal string Add (IWebSocketSession session)
  391. {
  392. lock (_sync) {
  393. if (_state != ServerState.Start)
  394. return null;
  395. var id = createID ();
  396. _sessions.Add (id, session);
  397. return id;
  398. }
  399. }
  400. internal bool Remove (string id)
  401. {
  402. lock (_sync)
  403. return _sessions.Remove (id);
  404. }
  405. internal void Start ()
  406. {
  407. lock (_sync) {
  408. _sweepTimer.Enabled = _keepClean;
  409. _state = ServerState.Start;
  410. }
  411. }
  412. internal void Stop (ushort code, string reason)
  413. {
  414. if (code == 1005) {
  415. stop (PayloadData.Empty, true);
  416. return;
  417. }
  418. var payloadData = new PayloadData (code, reason);
  419. var send = !code.IsReservedStatusCode ();
  420. stop (payloadData, send);
  421. }
  422. #endregion
  423. #region Public Methods
  424. /// <summary>
  425. /// Sends the specified data to every client in the WebSocket service.
  426. /// </summary>
  427. /// <param name="data">
  428. /// An array of <see cref="byte"/> that specifies the binary data to send.
  429. /// </param>
  430. /// <exception cref="InvalidOperationException">
  431. /// The current state of the service is not Start.
  432. /// </exception>
  433. /// <exception cref="ArgumentNullException">
  434. /// <paramref name="data"/> is <see langword="null"/>.
  435. /// </exception>
  436. public void Broadcast (byte[] data)
  437. {
  438. if (_state != ServerState.Start) {
  439. var msg = "The current state of the service is not Start.";
  440. throw new InvalidOperationException (msg);
  441. }
  442. if (data == null)
  443. throw new ArgumentNullException ("data");
  444. if (data.LongLength <= WebSocket.FragmentLength)
  445. broadcast (Opcode.Binary, data, null);
  446. else
  447. broadcast (Opcode.Binary, new MemoryStream (data), null);
  448. }
  449. /// <summary>
  450. /// Sends the specified data to every client in the WebSocket service.
  451. /// </summary>
  452. /// <param name="data">
  453. /// A <see cref="string"/> that specifies the text data to send.
  454. /// </param>
  455. /// <exception cref="InvalidOperationException">
  456. /// The current state of the service is not Start.
  457. /// </exception>
  458. /// <exception cref="ArgumentNullException">
  459. /// <paramref name="data"/> is <see langword="null"/>.
  460. /// </exception>
  461. /// <exception cref="ArgumentException">
  462. /// <paramref name="data"/> could not be UTF-8-encoded.
  463. /// </exception>
  464. public void Broadcast (string data)
  465. {
  466. if (_state != ServerState.Start) {
  467. var msg = "The current state of the service is not Start.";
  468. throw new InvalidOperationException (msg);
  469. }
  470. if (data == null)
  471. throw new ArgumentNullException ("data");
  472. byte[] bytes;
  473. if (!data.TryGetUTF8EncodedBytes (out bytes)) {
  474. var msg = "It could not be UTF-8-encoded.";
  475. throw new ArgumentException (msg, "data");
  476. }
  477. if (bytes.LongLength <= WebSocket.FragmentLength)
  478. broadcast (Opcode.Text, bytes, null);
  479. else
  480. broadcast (Opcode.Text, new MemoryStream (bytes), null);
  481. }
  482. /// <summary>
  483. /// Sends the data from the specified stream instance to every client in
  484. /// the WebSocket service.
  485. /// </summary>
  486. /// <param name="stream">
  487. /// <para>
  488. /// A <see cref="Stream"/> instance from which to read the data to send.
  489. /// </para>
  490. /// <para>
  491. /// The data is sent as the binary data.
  492. /// </para>
  493. /// </param>
  494. /// <param name="length">
  495. /// An <see cref="int"/> that specifies the number of bytes to send.
  496. /// </param>
  497. /// <exception cref="InvalidOperationException">
  498. /// The current state of the service is not Start.
  499. /// </exception>
  500. /// <exception cref="ArgumentNullException">
  501. /// <paramref name="stream"/> is <see langword="null"/>.
  502. /// </exception>
  503. /// <exception cref="ArgumentException">
  504. /// <para>
  505. /// <paramref name="stream"/> cannot be read.
  506. /// </para>
  507. /// <para>
  508. /// -or-
  509. /// </para>
  510. /// <para>
  511. /// <paramref name="length"/> is less than 1.
  512. /// </para>
  513. /// <para>
  514. /// -or-
  515. /// </para>
  516. /// <para>
  517. /// No data could be read from <paramref name="stream"/>.
  518. /// </para>
  519. /// </exception>
  520. public void Broadcast (Stream stream, int length)
  521. {
  522. if (_state != ServerState.Start) {
  523. var msg = "The current state of the service is not Start.";
  524. throw new InvalidOperationException (msg);
  525. }
  526. if (stream == null)
  527. throw new ArgumentNullException ("stream");
  528. if (!stream.CanRead) {
  529. var msg = "It cannot be read.";
  530. throw new ArgumentException (msg, "stream");
  531. }
  532. if (length < 1) {
  533. var msg = "Less than 1.";
  534. throw new ArgumentException (msg, "length");
  535. }
  536. var bytes = stream.ReadBytes (length);
  537. var len = bytes.Length;
  538. if (len == 0) {
  539. var msg = "No data could be read from it.";
  540. throw new ArgumentException (msg, "stream");
  541. }
  542. if (len < length) {
  543. var fmt = "Only {0} byte(s) of data could be read from the stream.";
  544. var msg = String.Format (fmt, len);
  545. _log.Warn (msg);
  546. }
  547. if (len <= WebSocket.FragmentLength)
  548. broadcast (Opcode.Binary, bytes, null);
  549. else
  550. broadcast (Opcode.Binary, new MemoryStream (bytes), null);
  551. }
  552. /// <summary>
  553. /// Sends the specified data to every client in the WebSocket service
  554. /// asynchronously.
  555. /// </summary>
  556. /// <remarks>
  557. /// This method does not wait for the send to be complete.
  558. /// </remarks>
  559. /// <param name="data">
  560. /// An array of <see cref="byte"/> that specifies the binary data to send.
  561. /// </param>
  562. /// <param name="completed">
  563. /// <para>
  564. /// An <see cref="Action"/> delegate.
  565. /// </para>
  566. /// <para>
  567. /// The delegate invokes the method called when the send is complete.
  568. /// </para>
  569. /// <para>
  570. /// <see langword="null"/> if not necessary.
  571. /// </para>
  572. /// </param>
  573. /// <exception cref="InvalidOperationException">
  574. /// The current state of the service is not Start.
  575. /// </exception>
  576. /// <exception cref="ArgumentNullException">
  577. /// <paramref name="data"/> is <see langword="null"/>.
  578. /// </exception>
  579. public void BroadcastAsync (byte[] data, Action completed)
  580. {
  581. if (_state != ServerState.Start) {
  582. var msg = "The current state of the service is not Start.";
  583. throw new InvalidOperationException (msg);
  584. }
  585. if (data == null)
  586. throw new ArgumentNullException ("data");
  587. if (data.LongLength <= WebSocket.FragmentLength)
  588. broadcastAsync (Opcode.Binary, data, completed);
  589. else
  590. broadcastAsync (Opcode.Binary, new MemoryStream (data), completed);
  591. }
  592. /// <summary>
  593. /// Sends the specified data to every client in the WebSocket service
  594. /// asynchronously.
  595. /// </summary>
  596. /// <remarks>
  597. /// This method does not wait for the send to be complete.
  598. /// </remarks>
  599. /// <param name="data">
  600. /// A <see cref="string"/> that specifies the text data to send.
  601. /// </param>
  602. /// <param name="completed">
  603. /// <para>
  604. /// An <see cref="Action"/> delegate.
  605. /// </para>
  606. /// <para>
  607. /// The delegate invokes the method called when the send is complete.
  608. /// </para>
  609. /// <para>
  610. /// <see langword="null"/> if not necessary.
  611. /// </para>
  612. /// </param>
  613. /// <exception cref="InvalidOperationException">
  614. /// The current state of the service is not Start.
  615. /// </exception>
  616. /// <exception cref="ArgumentNullException">
  617. /// <paramref name="data"/> is <see langword="null"/>.
  618. /// </exception>
  619. /// <exception cref="ArgumentException">
  620. /// <paramref name="data"/> could not be UTF-8-encoded.
  621. /// </exception>
  622. public void BroadcastAsync (string data, Action completed)
  623. {
  624. if (_state != ServerState.Start) {
  625. var msg = "The current state of the service is not Start.";
  626. throw new InvalidOperationException (msg);
  627. }
  628. if (data == null)
  629. throw new ArgumentNullException ("data");
  630. byte[] bytes;
  631. if (!data.TryGetUTF8EncodedBytes (out bytes)) {
  632. var msg = "It could not be UTF-8-encoded.";
  633. throw new ArgumentException (msg, "data");
  634. }
  635. if (bytes.LongLength <= WebSocket.FragmentLength)
  636. broadcastAsync (Opcode.Text, bytes, completed);
  637. else
  638. broadcastAsync (Opcode.Text, new MemoryStream (bytes), completed);
  639. }
  640. /// <summary>
  641. /// Sends the data from the specified stream instance to every client in
  642. /// the WebSocket service asynchronously.
  643. /// </summary>
  644. /// <remarks>
  645. /// This method does not wait for the send to be complete.
  646. /// </remarks>
  647. /// <param name="stream">
  648. /// <para>
  649. /// A <see cref="Stream"/> instance from which to read the data to send.
  650. /// </para>
  651. /// <para>
  652. /// The data is sent as the binary data.
  653. /// </para>
  654. /// </param>
  655. /// <param name="length">
  656. /// An <see cref="int"/> that specifies the number of bytes to send.
  657. /// </param>
  658. /// <param name="completed">
  659. /// <para>
  660. /// An <see cref="Action"/> delegate.
  661. /// </para>
  662. /// <para>
  663. /// The delegate invokes the method called when the send is complete.
  664. /// </para>
  665. /// <para>
  666. /// <see langword="null"/> if not necessary.
  667. /// </para>
  668. /// </param>
  669. /// <exception cref="InvalidOperationException">
  670. /// The current state of the service is not Start.
  671. /// </exception>
  672. /// <exception cref="ArgumentNullException">
  673. /// <paramref name="stream"/> is <see langword="null"/>.
  674. /// </exception>
  675. /// <exception cref="ArgumentException">
  676. /// <para>
  677. /// <paramref name="stream"/> cannot be read.
  678. /// </para>
  679. /// <para>
  680. /// -or-
  681. /// </para>
  682. /// <para>
  683. /// <paramref name="length"/> is less than 1.
  684. /// </para>
  685. /// <para>
  686. /// -or-
  687. /// </para>
  688. /// <para>
  689. /// No data could be read from <paramref name="stream"/>.
  690. /// </para>
  691. /// </exception>
  692. public void BroadcastAsync (Stream stream, int length, Action completed)
  693. {
  694. if (_state != ServerState.Start) {
  695. var msg = "The current state of the service is not Start.";
  696. throw new InvalidOperationException (msg);
  697. }
  698. if (stream == null)
  699. throw new ArgumentNullException ("stream");
  700. if (!stream.CanRead) {
  701. var msg = "It cannot be read.";
  702. throw new ArgumentException (msg, "stream");
  703. }
  704. if (length < 1) {
  705. var msg = "Less than 1.";
  706. throw new ArgumentException (msg, "length");
  707. }
  708. var bytes = stream.ReadBytes (length);
  709. var len = bytes.Length;
  710. if (len == 0) {
  711. var msg = "No data could be read from it.";
  712. throw new ArgumentException (msg, "stream");
  713. }
  714. if (len < length) {
  715. var fmt = "Only {0} byte(s) of data could be read from the stream.";
  716. var msg = String.Format (fmt, len);
  717. _log.Warn (msg);
  718. }
  719. if (len <= WebSocket.FragmentLength)
  720. broadcastAsync (Opcode.Binary, bytes, completed);
  721. else
  722. broadcastAsync (Opcode.Binary, new MemoryStream (bytes), completed);
  723. }
  724. /// <summary>
  725. /// Closes the session with the specified ID.
  726. /// </summary>
  727. /// <param name="id">
  728. /// A <see cref="string"/> that specifies the ID of the session to close.
  729. /// </param>
  730. /// <exception cref="ArgumentNullException">
  731. /// <paramref name="id"/> is <see langword="null"/>.
  732. /// </exception>
  733. /// <exception cref="ArgumentException">
  734. /// <paramref name="id"/> is an empty string.
  735. /// </exception>
  736. /// <exception cref="InvalidOperationException">
  737. /// The session could not be found.
  738. /// </exception>
  739. public void CloseSession (string id)
  740. {
  741. IWebSocketSession session;
  742. if (!TryGetSession (id, out session)) {
  743. var msg = "The session could not be found.";
  744. throw new InvalidOperationException (msg);
  745. }
  746. session.WebSocket.Close ();
  747. }
  748. /// <summary>
  749. /// Closes the session with the specified ID, code, and reason.
  750. /// </summary>
  751. /// <param name="id">
  752. /// A <see cref="string"/> that specifies the ID of the session to close.
  753. /// </param>
  754. /// <param name="code">
  755. /// <para>
  756. /// A <see cref="ushort"/> that specifies the status code indicating
  757. /// the reason for the close.
  758. /// </para>
  759. /// <para>
  760. /// The status codes are defined in
  761. /// <see href="http://tools.ietf.org/html/rfc6455#section-7.4">
  762. /// Section 7.4</see> of RFC 6455.
  763. /// </para>
  764. /// </param>
  765. /// <param name="reason">
  766. /// <para>
  767. /// A <see cref="string"/> that specifies the reason for the close.
  768. /// </para>
  769. /// <para>
  770. /// Its size must be 123 bytes or less in UTF-8.
  771. /// </para>
  772. /// </param>
  773. /// <exception cref="ArgumentNullException">
  774. /// <paramref name="id"/> is <see langword="null"/>.
  775. /// </exception>
  776. /// <exception cref="ArgumentException">
  777. /// <para>
  778. /// <paramref name="id"/> is an empty string.
  779. /// </para>
  780. /// <para>
  781. /// -or-
  782. /// </para>
  783. /// <para>
  784. /// <paramref name="code"/> is 1010 (mandatory extension).
  785. /// </para>
  786. /// <para>
  787. /// -or-
  788. /// </para>
  789. /// <para>
  790. /// <paramref name="code"/> is 1005 (no status) and
  791. /// <paramref name="reason"/> is specified.
  792. /// </para>
  793. /// <para>
  794. /// -or-
  795. /// </para>
  796. /// <para>
  797. /// <paramref name="reason"/> could not be UTF-8-encoded.
  798. /// </para>
  799. /// </exception>
  800. /// <exception cref="InvalidOperationException">
  801. /// The session could not be found.
  802. /// </exception>
  803. /// <exception cref="ArgumentOutOfRangeException">
  804. /// <para>
  805. /// <paramref name="code"/> is less than 1000 or greater than 4999.
  806. /// </para>
  807. /// <para>
  808. /// -or-
  809. /// </para>
  810. /// <para>
  811. /// The size of <paramref name="reason"/> is greater than 123 bytes.
  812. /// </para>
  813. /// </exception>
  814. public void CloseSession (string id, ushort code, string reason)
  815. {
  816. IWebSocketSession session;
  817. if (!TryGetSession (id, out session)) {
  818. var msg = "The session could not be found.";
  819. throw new InvalidOperationException (msg);
  820. }
  821. session.WebSocket.Close (code, reason);
  822. }
  823. /// <summary>
  824. /// Closes the session with the specified ID, code, and reason.
  825. /// </summary>
  826. /// <param name="id">
  827. /// A <see cref="string"/> that specifies the ID of the session to close.
  828. /// </param>
  829. /// <param name="code">
  830. /// <para>
  831. /// One of the <see cref="CloseStatusCode"/> enum values.
  832. /// </para>
  833. /// <para>
  834. /// It specifies the status code indicating the reason for the close.
  835. /// </para>
  836. /// </param>
  837. /// <param name="reason">
  838. /// <para>
  839. /// A <see cref="string"/> that specifies the reason for the close.
  840. /// </para>
  841. /// <para>
  842. /// Its size must be 123 bytes or less in UTF-8.
  843. /// </para>
  844. /// </param>
  845. /// <exception cref="ArgumentNullException">
  846. /// <paramref name="id"/> is <see langword="null"/>.
  847. /// </exception>
  848. /// <exception cref="ArgumentException">
  849. /// <para>
  850. /// <paramref name="id"/> is an empty string.
  851. /// </para>
  852. /// <para>
  853. /// -or-
  854. /// </para>
  855. /// <para>
  856. /// <paramref name="code"/> is <see cref="CloseStatusCode.MandatoryExtension"/>.
  857. /// </para>
  858. /// <para>
  859. /// -or-
  860. /// </para>
  861. /// <para>
  862. /// <paramref name="code"/> is <see cref="CloseStatusCode.NoStatus"/> and
  863. /// <paramref name="reason"/> is specified.
  864. /// </para>
  865. /// <para>
  866. /// -or-
  867. /// </para>
  868. /// <para>
  869. /// <paramref name="reason"/> could not be UTF-8-encoded.
  870. /// </para>
  871. /// </exception>
  872. /// <exception cref="InvalidOperationException">
  873. /// The session could not be found.
  874. /// </exception>
  875. /// <exception cref="ArgumentOutOfRangeException">
  876. /// The size of <paramref name="reason"/> is greater than 123 bytes.
  877. /// </exception>
  878. public void CloseSession (string id, CloseStatusCode code, string reason)
  879. {
  880. IWebSocketSession session;
  881. if (!TryGetSession (id, out session)) {
  882. var msg = "The session could not be found.";
  883. throw new InvalidOperationException (msg);
  884. }
  885. session.WebSocket.Close (code, reason);
  886. }
  887. /// <summary>
  888. /// Sends a ping to the client using the specified session.
  889. /// </summary>
  890. /// <returns>
  891. /// <c>true</c> if the send has successfully done and a pong has been
  892. /// received within a time; otherwise, <c>false</c>.
  893. /// </returns>
  894. /// <param name="id">
  895. /// A <see cref="string"/> that specifies the ID of the session.
  896. /// </param>
  897. /// <exception cref="ArgumentNullException">
  898. /// <paramref name="id"/> is <see langword="null"/>.
  899. /// </exception>
  900. /// <exception cref="ArgumentException">
  901. /// <paramref name="id"/> is an empty string.
  902. /// </exception>
  903. /// <exception cref="InvalidOperationException">
  904. /// The session could not be found.
  905. /// </exception>
  906. public bool PingTo (string id)
  907. {
  908. IWebSocketSession session;
  909. if (!TryGetSession (id, out session)) {
  910. var msg = "The session could not be found.";
  911. throw new InvalidOperationException (msg);
  912. }
  913. return session.WebSocket.Ping ();
  914. }
  915. /// <summary>
  916. /// Sends a ping with the specified message to the client using
  917. /// the specified session.
  918. /// </summary>
  919. /// <returns>
  920. /// <c>true</c> if the send has successfully done and a pong has been
  921. /// received within a time; otherwise, <c>false</c>.
  922. /// </returns>
  923. /// <param name="message">
  924. /// <para>
  925. /// A <see cref="string"/> that specifies the message to send.
  926. /// </para>
  927. /// <para>
  928. /// Its size must be 125 bytes or less in UTF-8.
  929. /// </para>
  930. /// </param>
  931. /// <param name="id">
  932. /// A <see cref="string"/> that specifies the ID of the session.
  933. /// </param>
  934. /// <exception cref="ArgumentNullException">
  935. /// <paramref name="id"/> is <see langword="null"/>.
  936. /// </exception>
  937. /// <exception cref="ArgumentException">
  938. /// <para>
  939. /// <paramref name="id"/> is an empty string.
  940. /// </para>
  941. /// <para>
  942. /// -or-
  943. /// </para>
  944. /// <para>
  945. /// <paramref name="message"/> could not be UTF-8-encoded.
  946. /// </para>
  947. /// </exception>
  948. /// <exception cref="InvalidOperationException">
  949. /// The session could not be found.
  950. /// </exception>
  951. /// <exception cref="ArgumentOutOfRangeException">
  952. /// The size of <paramref name="message"/> is greater than 125 bytes.
  953. /// </exception>
  954. public bool PingTo (string message, string id)
  955. {
  956. IWebSocketSession session;
  957. if (!TryGetSession (id, out session)) {
  958. var msg = "The session could not be found.";
  959. throw new InvalidOperationException (msg);
  960. }
  961. return session.WebSocket.Ping (message);
  962. }
  963. /// <summary>
  964. /// Sends the specified data to the client using the specified session.
  965. /// </summary>
  966. /// <param name="data">
  967. /// An array of <see cref="byte"/> that specifies the binary data to send.
  968. /// </param>
  969. /// <param name="id">
  970. /// A <see cref="string"/> that specifies the ID of the session.
  971. /// </param>
  972. /// <exception cref="ArgumentNullException">
  973. /// <para>
  974. /// <paramref name="id"/> is <see langword="null"/>.
  975. /// </para>
  976. /// <para>
  977. /// -or-
  978. /// </para>
  979. /// <para>
  980. /// <paramref name="data"/> is <see langword="null"/>.
  981. /// </para>
  982. /// </exception>
  983. /// <exception cref="ArgumentException">
  984. /// <paramref name="id"/> is an empty string.
  985. /// </exception>
  986. /// <exception cref="InvalidOperationException">
  987. /// <para>
  988. /// The session could not be found.
  989. /// </para>
  990. /// <para>
  991. /// -or-
  992. /// </para>
  993. /// <para>
  994. /// The current state of the WebSocket interface is not Open.
  995. /// </para>
  996. /// </exception>
  997. public void SendTo (byte[] data, string id)
  998. {
  999. IWebSocketSession session;
  1000. if (!TryGetSession (id, out session)) {
  1001. var msg = "The session could not be found.";
  1002. throw new InvalidOperationException (msg);
  1003. }
  1004. session.WebSocket.Send (data);
  1005. }
  1006. /// <summary>
  1007. /// Sends the specified data to the client using the specified session.
  1008. /// </summary>
  1009. /// <param name="data">
  1010. /// A <see cref="string"/> that specifies the text data to send.
  1011. /// </param>
  1012. /// <param name="id">
  1013. /// A <see cref="string"/> that specifies the ID of the session.
  1014. /// </param>
  1015. /// <exception cref="ArgumentNullException">
  1016. /// <para>
  1017. /// <paramref name="id"/> is <see langword="null"/>.
  1018. /// </para>
  1019. /// <para>
  1020. /// -or-
  1021. /// </para>
  1022. /// <para>
  1023. /// <paramref name="data"/> is <see langword="null"/>.
  1024. /// </para>
  1025. /// </exception>
  1026. /// <exception cref="ArgumentException">
  1027. /// <para>
  1028. /// <paramref name="id"/> is an empty string.
  1029. /// </para>
  1030. /// <para>
  1031. /// -or-
  1032. /// </para>
  1033. /// <para>
  1034. /// <paramref name="data"/> could not be UTF-8-encoded.
  1035. /// </para>
  1036. /// </exception>
  1037. /// <exception cref="InvalidOperationException">
  1038. /// <para>
  1039. /// The session could not be found.
  1040. /// </para>
  1041. /// <para>
  1042. /// -or-
  1043. /// </para>
  1044. /// <para>
  1045. /// The current state of the WebSocket interface is not Open.
  1046. /// </para>
  1047. /// </exception>
  1048. public void SendTo (string data, string id)
  1049. {
  1050. IWebSocketSession session;
  1051. if (!TryGetSession (id, out session)) {
  1052. var msg = "The session could not be found.";
  1053. throw new InvalidOperationException (msg);
  1054. }
  1055. session.WebSocket.Send (data);
  1056. }
  1057. /// <summary>
  1058. /// Sends the data from the specified stream instance to the client using
  1059. /// the specified session.
  1060. /// </summary>
  1061. /// <param name="stream">
  1062. /// <para>
  1063. /// A <see cref="Stream"/> instance from which to read the data to send.
  1064. /// </para>
  1065. /// <para>
  1066. /// The data is sent as the binary data.
  1067. /// </para>
  1068. /// </param>
  1069. /// <param name="length">
  1070. /// An <see cref="int"/> that specifies the number of bytes to send.
  1071. /// </param>
  1072. /// <param name="id">
  1073. /// A <see cref="string"/> that specifies the ID of the session.
  1074. /// </param>
  1075. /// <exception cref="ArgumentNullException">
  1076. /// <para>
  1077. /// <paramref name="id"/> is <see langword="null"/>.
  1078. /// </para>
  1079. /// <para>
  1080. /// -or-
  1081. /// </para>
  1082. /// <para>
  1083. /// <paramref name="stream"/> is <see langword="null"/>.
  1084. /// </para>
  1085. /// </exception>
  1086. /// <exception cref="ArgumentException">
  1087. /// <para>
  1088. /// <paramref name="id"/> is an empty string.
  1089. /// </para>
  1090. /// <para>
  1091. /// -or-
  1092. /// </para>
  1093. /// <para>
  1094. /// <paramref name="stream"/> cannot be read.
  1095. /// </para>
  1096. /// <para>
  1097. /// -or-
  1098. /// </para>
  1099. /// <para>
  1100. /// <paramref name="length"/> is less than 1.
  1101. /// </para>
  1102. /// <para>
  1103. /// -or-
  1104. /// </para>
  1105. /// <para>
  1106. /// No data could be read from <paramref name="stream"/>.
  1107. /// </para>
  1108. /// </exception>
  1109. /// <exception cref="InvalidOperationException">
  1110. /// <para>
  1111. /// The session could not be found.
  1112. /// </para>
  1113. /// <para>
  1114. /// -or-
  1115. /// </para>
  1116. /// <para>
  1117. /// The current state of the WebSocket interface is not Open.
  1118. /// </para>
  1119. /// </exception>
  1120. public void SendTo (Stream stream, int length, string id)
  1121. {
  1122. IWebSocketSession session;
  1123. if (!TryGetSession (id, out session)) {
  1124. var msg = "The session could not be found.";
  1125. throw new InvalidOperationException (msg);
  1126. }
  1127. session.WebSocket.Send (stream, length);
  1128. }
  1129. /// <summary>
  1130. /// Sends the specified data to the client using the specified session
  1131. /// asynchronously.
  1132. /// </summary>
  1133. /// <remarks>
  1134. /// This method does not wait for the send to be complete.
  1135. /// </remarks>
  1136. /// <param name="data">
  1137. /// An array of <see cref="byte"/> that specifies the binary data to send.
  1138. /// </param>
  1139. /// <param name="id">
  1140. /// A <see cref="string"/> that specifies the ID of the session.
  1141. /// </param>
  1142. /// <param name="completed">
  1143. /// <para>
  1144. /// An <see cref="T:System.Action{bool}"/> delegate.
  1145. /// </para>
  1146. /// <para>
  1147. /// The delegate invokes the method called when the send is complete.
  1148. /// </para>
  1149. /// <para>
  1150. /// The <see cref="bool"/> parameter passed to the method is <c>true</c>
  1151. /// if the send has successfully done; otherwise, <c>false</c>.
  1152. /// </para>
  1153. /// <para>
  1154. /// <see langword="null"/> if not necessary.
  1155. /// </para>
  1156. /// </param>
  1157. /// <exception cref="ArgumentNullException">
  1158. /// <para>
  1159. /// <paramref name="id"/> is <see langword="null"/>.
  1160. /// </para>
  1161. /// <para>
  1162. /// -or-
  1163. /// </para>
  1164. /// <para>
  1165. /// <paramref name="data"/> is <see langword="null"/>.
  1166. /// </para>
  1167. /// </exception>
  1168. /// <exception cref="ArgumentException">
  1169. /// <paramref name="id"/> is an empty string.
  1170. /// </exception>
  1171. /// <exception cref="InvalidOperationException">
  1172. /// <para>
  1173. /// The session could not be found.
  1174. /// </para>
  1175. /// <para>
  1176. /// -or-
  1177. /// </para>
  1178. /// <para>
  1179. /// The current state of the WebSocket interface is not Open.
  1180. /// </para>
  1181. /// </exception>
  1182. public void SendToAsync (byte[] data, string id, Action<bool> completed)
  1183. {
  1184. IWebSocketSession session;
  1185. if (!TryGetSession (id, out session)) {
  1186. var msg = "The session could not be found.";
  1187. throw new InvalidOperationException (msg);
  1188. }
  1189. session.WebSocket.SendAsync (data, completed);
  1190. }
  1191. /// <summary>
  1192. /// Sends the specified data to the client using the specified session
  1193. /// asynchronously.
  1194. /// </summary>
  1195. /// <remarks>
  1196. /// This method does not wait for the send to be complete.
  1197. /// </remarks>
  1198. /// <param name="data">
  1199. /// A <see cref="string"/> that specifies the text data to send.
  1200. /// </param>
  1201. /// <param name="id">
  1202. /// A <see cref="string"/> that specifies the ID of the session.
  1203. /// </param>
  1204. /// <param name="completed">
  1205. /// <para>
  1206. /// An <see cref="T:System.Action{bool}"/> delegate.
  1207. /// </para>
  1208. /// <para>
  1209. /// The delegate invokes the method called when the send is complete.
  1210. /// </para>
  1211. /// <para>
  1212. /// The <see cref="bool"/> parameter passed to the method is <c>true</c>
  1213. /// if the send has successfully done; otherwise, <c>false</c>.
  1214. /// </para>
  1215. /// <para>
  1216. /// <see langword="null"/> if not necessary.
  1217. /// </para>
  1218. /// </param>
  1219. /// <exception cref="ArgumentNullException">
  1220. /// <para>
  1221. /// <paramref name="id"/> is <see langword="null"/>.
  1222. /// </para>
  1223. /// <para>
  1224. /// -or-
  1225. /// </para>
  1226. /// <para>
  1227. /// <paramref name="data"/> is <see langword="null"/>.
  1228. /// </para>
  1229. /// </exception>
  1230. /// <exception cref="ArgumentException">
  1231. /// <para>
  1232. /// <paramref name="id"/> is an empty string.
  1233. /// </para>
  1234. /// <para>
  1235. /// -or-
  1236. /// </para>
  1237. /// <para>
  1238. /// <paramref name="data"/> could not be UTF-8-encoded.
  1239. /// </para>
  1240. /// </exception>
  1241. /// <exception cref="InvalidOperationException">
  1242. /// <para>
  1243. /// The session could not be found.
  1244. /// </para>
  1245. /// <para>
  1246. /// -or-
  1247. /// </para>
  1248. /// <para>
  1249. /// The current state of the WebSocket interface is not Open.
  1250. /// </para>
  1251. /// </exception>
  1252. public void SendToAsync (string data, string id, Action<bool> completed)
  1253. {
  1254. IWebSocketSession session;
  1255. if (!TryGetSession (id, out session)) {
  1256. var msg = "The session could not be found.";
  1257. throw new InvalidOperationException (msg);
  1258. }
  1259. session.WebSocket.SendAsync (data, completed);
  1260. }
  1261. /// <summary>
  1262. /// Sends the data from the specified stream instance to the client using
  1263. /// the specified session asynchronously.
  1264. /// </summary>
  1265. /// <remarks>
  1266. /// This method does not wait for the send to be complete.
  1267. /// </remarks>
  1268. /// <param name="stream">
  1269. /// <para>
  1270. /// A <see cref="Stream"/> instance from which to read the data to send.
  1271. /// </para>
  1272. /// <para>
  1273. /// The data is sent as the binary data.
  1274. /// </para>
  1275. /// </param>
  1276. /// <param name="length">
  1277. /// An <see cref="int"/> that specifies the number of bytes to send.
  1278. /// </param>
  1279. /// <param name="id">
  1280. /// A <see cref="string"/> that specifies the ID of the session.
  1281. /// </param>
  1282. /// <param name="completed">
  1283. /// <para>
  1284. /// An <see cref="T:System.Action{bool}"/> delegate.
  1285. /// </para>
  1286. /// <para>
  1287. /// The delegate invokes the method called when the send is complete.
  1288. /// </para>
  1289. /// <para>
  1290. /// The <see cref="bool"/> parameter passed to the method is <c>true</c>
  1291. /// if the send has successfully done; otherwise, <c>false</c>.
  1292. /// </para>
  1293. /// <para>
  1294. /// <see langword="null"/> if not necessary.
  1295. /// </para>
  1296. /// </param>
  1297. /// <exception cref="ArgumentNullException">
  1298. /// <para>
  1299. /// <paramref name="id"/> is <see langword="null"/>.
  1300. /// </para>
  1301. /// <para>
  1302. /// -or-
  1303. /// </para>
  1304. /// <para>
  1305. /// <paramref name="stream"/> is <see langword="null"/>.
  1306. /// </para>
  1307. /// </exception>
  1308. /// <exception cref="ArgumentException">
  1309. /// <para>
  1310. /// <paramref name="id"/> is an empty string.
  1311. /// </para>
  1312. /// <para>
  1313. /// -or-
  1314. /// </para>
  1315. /// <para>
  1316. /// <paramref name="stream"/> cannot be read.
  1317. /// </para>
  1318. /// <para>
  1319. /// -or-
  1320. /// </para>
  1321. /// <para>
  1322. /// <paramref name="length"/> is less than 1.
  1323. /// </para>
  1324. /// <para>
  1325. /// -or-
  1326. /// </para>
  1327. /// <para>
  1328. /// No data could be read from <paramref name="stream"/>.
  1329. /// </para>
  1330. /// </exception>
  1331. /// <exception cref="InvalidOperationException">
  1332. /// <para>
  1333. /// The session could not be found.
  1334. /// </para>
  1335. /// <para>
  1336. /// -or-
  1337. /// </para>
  1338. /// <para>
  1339. /// The current state of the WebSocket interface is not Open.
  1340. /// </para>
  1341. /// </exception>
  1342. public void SendToAsync (
  1343. Stream stream, int length, string id, Action<bool> completed
  1344. )
  1345. {
  1346. IWebSocketSession session;
  1347. if (!TryGetSession (id, out session)) {
  1348. var msg = "The session could not be found.";
  1349. throw new InvalidOperationException (msg);
  1350. }
  1351. session.WebSocket.SendAsync (stream, length, completed);
  1352. }
  1353. /// <summary>
  1354. /// Cleans up the inactive sessions in the WebSocket service.
  1355. /// </summary>
  1356. public void Sweep ()
  1357. {
  1358. if (_sweeping) {
  1359. _log.Trace ("The sweep process is already in progress.");
  1360. return;
  1361. }
  1362. lock (_forSweep) {
  1363. if (_sweeping) {
  1364. _log.Trace ("The sweep process is already in progress.");
  1365. return;
  1366. }
  1367. _sweeping = true;
  1368. }
  1369. foreach (var id in InactiveIDs) {
  1370. if (_state != ServerState.Start)
  1371. break;
  1372. lock (_sync) {
  1373. if (_state != ServerState.Start)
  1374. break;
  1375. IWebSocketSession session;
  1376. if (!_sessions.TryGetValue (id, out session))
  1377. continue;
  1378. var state = session.WebSocket.ReadyState;
  1379. if (state == WebSocketState.Open) {
  1380. session.WebSocket.Close (CloseStatusCode.Abnormal);
  1381. continue;
  1382. }
  1383. if (state == WebSocketState.Closing)
  1384. continue;
  1385. _sessions.Remove (id);
  1386. }
  1387. }
  1388. _sweeping = false;
  1389. }
  1390. /// <summary>
  1391. /// Tries to get the session instance with the specified ID.
  1392. /// </summary>
  1393. /// <returns>
  1394. /// <c>true</c> if the session instance is successfully found; otherwise,
  1395. /// <c>false</c>.
  1396. /// </returns>
  1397. /// <param name="id">
  1398. /// A <see cref="string"/> that specifies the ID of the session to find.
  1399. /// </param>
  1400. /// <param name="session">
  1401. /// <para>
  1402. /// When this method returns, a <see cref="IWebSocketSession"/>
  1403. /// instance or <see langword="null"/> if not found.
  1404. /// </para>
  1405. /// <para>
  1406. /// The session instance provides the function to access
  1407. /// the information in the session.
  1408. /// </para>
  1409. /// </param>
  1410. /// <exception cref="ArgumentNullException">
  1411. /// <paramref name="id"/> is <see langword="null"/>.
  1412. /// </exception>
  1413. /// <exception cref="ArgumentException">
  1414. /// <paramref name="id"/> is an empty string.
  1415. /// </exception>
  1416. public bool TryGetSession (string id, out IWebSocketSession session)
  1417. {
  1418. if (id == null)
  1419. throw new ArgumentNullException ("id");
  1420. if (id.Length == 0)
  1421. throw new ArgumentException ("An empty string.", "id");
  1422. return tryGetSession (id, out session);
  1423. }
  1424. #endregion
  1425. }
  1426. }