DownStreamSample.cs 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. using System.Collections;
  2. using System.Text;
  3. using Best.HTTP.Examples.Helpers;
  4. using Best.HTTP.Response;
  5. using UnityEngine;
  6. namespace Best.HTTP.Examples
  7. {
  8. /// <summary>
  9. /// Example showing the usage of download streaming using the DownloadContentStream class.
  10. /// In this example content processing is done on the Unity main thread wrapped in a coroutine.
  11. /// </summary>
  12. class DownStreamSample : SampleBase
  13. {
  14. #pragma warning disable 0649, 0169
  15. [Header("Sample Fields")]
  16. /// <summary>
  17. /// GameObject that will be used as a root for new UI objects.
  18. /// </summary>
  19. [SerializeField]
  20. private RectTransform _contentRoot;
  21. /// <summary>
  22. /// Prefab of a UI object with a Text field.
  23. /// </summary>
  24. [SerializeField]
  25. private TextListItem _listItemPrefab;
  26. #pragma warning restore
  27. /// <summary>
  28. /// Address of the used end point.
  29. /// </summary>
  30. private string _baseAddress = "https://besthttpwebgldemo.azurewebsites.net/sse";
  31. /// <summary>
  32. /// Cached reference to the HTTPRequest instance.
  33. /// </summary>
  34. private HTTPRequest _request;
  35. protected override void Start()
  36. {
  37. base.Start();
  38. // Create a regular get request with a regular callback too. We still need a callback,
  39. // because it might encounter an error before able to start a download.
  40. _request = HTTPRequest.CreateGet(this._baseAddress, OnRequestFinishedCallack);
  41. // Request a notification when download starts. This callback will be fired when
  42. // the status code suggests that we can expect actual content (2xx status codes).
  43. _request.DownloadSettings.OnDownloadStarted += OnDownloadStarted;
  44. // Don't want to retry when there's a failure
  45. _request.RetrySettings.MaxRetries = 0;
  46. // Start processing the request
  47. _request.Send();
  48. AddUIText("Connecting...");
  49. }
  50. private void OnDownloadStarted(HTTPRequest req, HTTPResponse resp, DownloadContentStream stream)
  51. {
  52. AddUIText("Download started!");
  53. // We can expect content from the server, start our logic.
  54. StartCoroutine(ParseContent(stream));
  55. }
  56. IEnumerator ParseContent(DownloadContentStream stream)
  57. {
  58. try
  59. {
  60. while (!stream.IsCompleted)
  61. {
  62. // Try to take out a download segment from the Download Stream.
  63. if (stream.TryTake(out var buffer))
  64. {
  65. // Make sure that the buffer is released back to the BufferPool.
  66. using var _ = buffer.AsAutoRelease();
  67. try
  68. {
  69. // Try to create a string from the downloaded content
  70. var str = Encoding.UTF8.GetString(buffer.Data, buffer.Offset, buffer.Count).TrimEnd();
  71. // And display it in the UI
  72. AddUIText(str);
  73. }
  74. catch { }
  75. }
  76. yield return null;
  77. }
  78. }
  79. finally
  80. {
  81. // Don't forget to Dispose the stream!
  82. stream.Dispose();
  83. }
  84. }
  85. private void OnRequestFinishedCallack(HTTPRequest req, HTTPResponse resp)
  86. {
  87. if (_request == null)
  88. return;
  89. string log = null;
  90. if (req.State == HTTPRequestStates.Finished)
  91. {
  92. if (!resp.IsSuccess)
  93. log = resp.StatusCode.ToString();
  94. }
  95. else
  96. log = req.State.ToString();
  97. AddUIText(log);
  98. _request = null;
  99. }
  100. private void OnDestroy()
  101. {
  102. _request?.Abort();
  103. _request = null;
  104. }
  105. void AddUIText(string text)
  106. => Instantiate<TextListItem>(this._listItemPrefab, this._contentRoot)
  107. .SetText(text);
  108. }
  109. }