CloseEventArgs.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 => _code;
  45. /// <summary>
  46. /// Gets the reason for the close.
  47. /// </summary>
  48. /// <value>
  49. /// A <see cref="string"/> that represents the reason for the close if any.
  50. /// </value>
  51. public string Reason => _reason;
  52. /// <summary>
  53. /// Gets a value indicating whether the WebSocket connection has been closed cleanly.
  54. /// </summary>
  55. /// <value>
  56. /// <c>true</c> if the WebSocket connection has been closed cleanly; otherwise, <c>false</c>.
  57. /// </value>
  58. public bool WasClean
  59. {
  60. get => _clean;
  61. internal set => _clean = value;
  62. }
  63. #endregion
  64. }
  65. }