CloseEventArgs.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System;
  2. using System.Text;
  3. namespace SocketHttpListener
  4. {
  5. /// <summary>
  6. /// Contains the event data associated with a <see cref="WebSocket.OnClose"/> event.
  7. /// </summary>
  8. /// <remarks>
  9. /// A <see cref="WebSocket.OnClose"/> event occurs when the WebSocket connection has been closed.
  10. /// If you would like to get the reason for the close, you should access the <see cref="Code"/> or
  11. /// <see cref="Reason"/> property.
  12. /// </remarks>
  13. public class CloseEventArgs : EventArgs
  14. {
  15. #region Private Fields
  16. private bool _clean;
  17. private ushort _code;
  18. private string _reason;
  19. #endregion
  20. #region Internal Constructors
  21. internal CloseEventArgs (PayloadData payload)
  22. {
  23. var data = payload.ApplicationData;
  24. var len = data.Length;
  25. _code = len > 1
  26. ? data.SubArray (0, 2).ToUInt16 (ByteOrder.Big)
  27. : (ushort) CloseStatusCode.NoStatusCode;
  28. _reason = len > 2
  29. ? GetUtf8String(data.SubArray (2, len - 2))
  30. : String.Empty;
  31. }
  32. private string GetUtf8String(byte[] bytes)
  33. {
  34. return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
  35. }
  36. #endregion
  37. #region Public Properties
  38. /// <summary>
  39. /// Gets the status code for the close.
  40. /// </summary>
  41. /// <value>
  42. /// A <see cref="ushort"/> that represents the status code for the close if any.
  43. /// </value>
  44. public ushort Code {
  45. get {
  46. return _code;
  47. }
  48. }
  49. /// <summary>
  50. /// Gets the reason for the close.
  51. /// </summary>
  52. /// <value>
  53. /// A <see cref="string"/> that represents the reason for the close if any.
  54. /// </value>
  55. public string Reason {
  56. get {
  57. return _reason;
  58. }
  59. }
  60. /// <summary>
  61. /// Gets a value indicating whether the WebSocket connection has been closed cleanly.
  62. /// </summary>
  63. /// <value>
  64. /// <c>true</c> if the WebSocket connection has been closed cleanly; otherwise, <c>false</c>.
  65. /// </value>
  66. public bool WasClean {
  67. get {
  68. return _clean;
  69. }
  70. internal set {
  71. _clean = value;
  72. }
  73. }
  74. #endregion
  75. }
  76. }