EventMessage.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using SocketIOClient.Transport;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Text.Json;
  5. namespace SocketIOClient.Messages
  6. {
  7. public class EventMessage : IMessage
  8. {
  9. public MessageType Type => MessageType.EventMessage;
  10. public string Namespace { get; set; }
  11. public string Event { get; set; }
  12. public int Id { get; set; }
  13. public List<JsonElement> JsonElements { get; set; }
  14. public string Json { get; set; }
  15. public List<byte[]> OutgoingBytes { get; set; }
  16. public List<byte[]> IncomingBytes { get; set; }
  17. public int BinaryCount { get; }
  18. public int Eio { get; set; }
  19. public TransportProtocol Protocol { get; set; }
  20. public void Read(string msg)
  21. {
  22. int index = msg.IndexOf('[');
  23. int lastIndex = msg.LastIndexOf(',', index);
  24. if (lastIndex > -1)
  25. {
  26. string text = msg.Substring(0, index);
  27. Namespace = text.Substring(0, lastIndex);
  28. if (index - lastIndex > 1)
  29. {
  30. Id = int.Parse(text.Substring(lastIndex + 1));
  31. }
  32. }
  33. else
  34. {
  35. if (index > 0)
  36. {
  37. Id = int.Parse(msg.Substring(0, index));
  38. }
  39. }
  40. msg = msg.Substring(index);
  41. //int index = msg.IndexOf('[');
  42. //if (index > 0)
  43. //{
  44. // Namespace = msg.Substring(0, index - 1);
  45. // msg = msg.Substring(index);
  46. //}
  47. var array = JsonDocument.Parse(msg).RootElement.EnumerateArray();
  48. int i = -1;
  49. foreach (var item in array)
  50. {
  51. i++;
  52. if (i == 0)
  53. {
  54. Event = item.GetString();
  55. JsonElements = new List<JsonElement>();
  56. }
  57. else
  58. {
  59. JsonElements.Add(item);
  60. }
  61. }
  62. }
  63. public string Write()
  64. {
  65. var builder = new StringBuilder();
  66. builder.Append("42");
  67. if (!string.IsNullOrEmpty(Namespace))
  68. {
  69. builder.Append(Namespace).Append(',');
  70. }
  71. if (string.IsNullOrEmpty(Json))
  72. {
  73. builder.Append("[\"").Append(Event).Append("\"]");
  74. }
  75. else
  76. {
  77. string data = Json.Insert(1, $"\"{Event}\",");
  78. builder.Append(data);
  79. }
  80. return builder.ToString();
  81. }
  82. }
  83. }