CloseEventArgs.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 static 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. {
  46. get
  47. {
  48. return _code;
  49. }
  50. }
  51. /// <summary>
  52. /// Gets the reason for the close.
  53. /// </summary>
  54. /// <value>
  55. /// A <see cref="string"/> that represents the reason for the close if any.
  56. /// </value>
  57. public string Reason
  58. {
  59. get
  60. {
  61. return _reason;
  62. }
  63. }
  64. /// <summary>
  65. /// Gets a value indicating whether the WebSocket connection has been closed cleanly.
  66. /// </summary>
  67. /// <value>
  68. /// <c>true</c> if the WebSocket connection has been closed cleanly; otherwise, <c>false</c>.
  69. /// </value>
  70. public bool WasClean
  71. {
  72. get
  73. {
  74. return _clean;
  75. }
  76. internal set
  77. {
  78. _clean = value;
  79. }
  80. }
  81. #endregion
  82. }
  83. }