Eio3HttpPollingHandler.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System.Collections.Generic;
  2. using System.Net.Http;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using System.Linq;
  6. using System.Net.Http.Headers;
  7. namespace SocketIOClient.Transport
  8. {
  9. public class Eio3HttpPollingHandler : HttpPollingHandler
  10. {
  11. public Eio3HttpPollingHandler(HttpClient httpClient) : base(httpClient) { }
  12. public override async Task PostAsync(string uri, IEnumerable<byte[]> bytes, CancellationToken cancellationToken)
  13. {
  14. var list = new List<byte>();
  15. foreach (var item in bytes)
  16. {
  17. list.Add(1);
  18. var length = SplitInt(item.Length + 1).Select(x => (byte)x);
  19. list.AddRange(length);
  20. list.Add(byte.MaxValue);
  21. list.Add(4);
  22. list.AddRange(item);
  23. }
  24. var content = new ByteArrayContent(list.ToArray());
  25. content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
  26. await HttpClient.PostAsync(AppendRandom(uri), content, cancellationToken).ConfigureAwait(false);
  27. }
  28. private List<int> SplitInt(int number)
  29. {
  30. List<int> list = new List<int>();
  31. while (number > 0)
  32. {
  33. list.Add(number % 10);
  34. number /= 10;
  35. }
  36. list.Reverse();
  37. return list;
  38. }
  39. protected override void ProduceText(string text)
  40. {
  41. int p = 0;
  42. while (true)
  43. {
  44. int index = text.IndexOf(':', p);
  45. if (index == -1)
  46. {
  47. break;
  48. }
  49. if (int.TryParse(text.Substring(p, index - p), out int length))
  50. {
  51. string msg = text.Substring(index + 1, length);
  52. TextSubject.OnNext(msg);
  53. }
  54. else
  55. {
  56. break;
  57. }
  58. p = index + length + 1;
  59. if (p >= text.Length)
  60. {
  61. break;
  62. }
  63. }
  64. }
  65. public override Task PostAsync(string uri, string content, CancellationToken cancellationToken)
  66. {
  67. content = content.Length + ":" + content;
  68. return base.PostAsync(uri, content, cancellationToken);
  69. }
  70. }
  71. }