MessageEventArgs.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.Text;
  3. namespace SocketHttpListener
  4. {
  5. /// <summary>
  6. /// Contains the event data associated with a <see cref="WebSocket.OnMessage"/> event.
  7. /// </summary>
  8. /// <remarks>
  9. /// A <see cref="WebSocket.OnMessage"/> event occurs when the <see cref="WebSocket"/> receives
  10. /// a text or binary data frame.
  11. /// If you want to get the received data, you access the <see cref="Data"/> or
  12. /// <see cref="RawData"/> property.
  13. /// </remarks>
  14. public class MessageEventArgs : EventArgs
  15. {
  16. #region Private Fields
  17. private string _data;
  18. private Opcode _opcode;
  19. private byte[] _rawData;
  20. #endregion
  21. #region Internal Constructors
  22. internal MessageEventArgs(Opcode opcode, byte[] data)
  23. {
  24. _opcode = opcode;
  25. _rawData = data;
  26. _data = convertToString(opcode, data);
  27. }
  28. internal MessageEventArgs(Opcode opcode, PayloadData payload)
  29. {
  30. _opcode = opcode;
  31. _rawData = payload.ApplicationData;
  32. _data = convertToString(opcode, _rawData);
  33. }
  34. #endregion
  35. #region Public Properties
  36. /// <summary>
  37. /// Gets the received data as a <see cref="string"/>.
  38. /// </summary>
  39. /// <value>
  40. /// A <see cref="string"/> that contains the received data.
  41. /// </value>
  42. public string Data => _data;
  43. /// <summary>
  44. /// Gets the received data as an array of <see cref="byte"/>.
  45. /// </summary>
  46. /// <value>
  47. /// An array of <see cref="byte"/> that contains the received data.
  48. /// </value>
  49. public byte[] RawData => _rawData;
  50. /// <summary>
  51. /// Gets the type of the received data.
  52. /// </summary>
  53. /// <value>
  54. /// One of the <see cref="Opcode"/> values, indicates the type of the received data.
  55. /// </value>
  56. public Opcode Type => _opcode;
  57. #endregion
  58. #region Private Methods
  59. private static string convertToString(Opcode opcode, byte[] data)
  60. {
  61. return data.Length == 0
  62. ? string.Empty
  63. : opcode == Opcode.Text
  64. ? Encoding.UTF8.GetString(data, 0, data.Length)
  65. : opcode.ToString();
  66. }
  67. #endregion
  68. }
  69. }