Search Unity

  1. Calling all beginners! Join the FPS Beginners Mods Challenge until December 13.
    Dismiss Notice
  2. It's Cyber Week at the Asset Store!
    Dismiss Notice

Best HTTP Released

Discussion in 'Assets and Asset Store' started by BestHTTP, Sep 11, 2013.

  1. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,383
    syscrusher and Cromfeli like this.
  2. b43-14brett647

    b43-14brett647

    Joined:
    Sep 9, 2015
    Posts:
    10
    Oh wow it actually works this time. Thanks!
     
    Cromfeli likes this.
  3. justtime

    justtime

    Joined:
    Oct 6, 2013
    Posts:
    337
    Hi there! After update to the latest version my download progress becomes more sharp and choppy, than before. How to make it smooth again?
    Before

    After


    Code
    Code (CSharp):
    1.  
    2. httpRequest.OnStreamingData += (req, resp, data, dataLength) => {
    3.     if (resp.IsSuccess)
    4.     {
    5.         // Write out the downloaded data to a file:
    6.         if (data != null)
    7.         {
    8.             using (FileStream fs = new FileStream(fileName, FileMode.Append))
    9.             {
    10.                 fs.Write(data, 0, dataLength);
    11.             }
    12.         }
    13.     }
    14.     else
    15.     {
    16.         //error handling
    17.  
    18.         return false;
    19.     }
    20.  
    21.     return true;
    22. };
    23.  
    24.  
    25. httpRequest.OnDownloadProgress = (req, downloaded, length) => { onTrackLoadingProgress(downloaded / (float) length); };
    26. httpRequest.StreamFragmentSize = 1 * 1024 * 1024; // 1 megabyte
    27. httpRequest.DisableCache = true; // already saving to a file, so turn off caching
    28. httpRequest.Send();
     
  4. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,383
    @justtime

    Do you use the OnDownloadProgress event to show the animation? That event usually fired more frequently than the OnStreamingData and doesn't depend on streaming settings.

    You can set the plugin's log level and send the logs to me. You can read about logging and where you can find the logs files here: https://besthttp-documentation.readthedocs.io/en/latest/#7. Global Topics/Logging/

    Edit: you shouldn't open the file in the OnStreamingData callback. You should create it once, and close it in the request's callback.
     
  5. justtime

    justtime

    Joined:
    Oct 6, 2013
    Posts:
    337
    In my case seems that it depends on StreamFragmentSize settings, because when i decrease this value, it is called more often.
    I have sent log file to you via pm.
    About file, do you mean something like this?
    Code (CSharp):
    1. FileStream fs = null;
    2. ...
    3. //in OnFinishedCallback
    4. fs?.Dispose();
    5. ...
    6. //in OnStreamingData Callback
    7. if (fs == null)
    8.                 {
    9.                     fs = new FileStream(fileName, FileMode.Append);
    10.                 }
    11. if (resp.IsSuccess)
    12.                 {
    13.                     // Write out the downloaded data to a file:
    14.                     if (data != null)
    15.                     {
    16.                         fs.Write(data, 0, dataLength);
    17.                     }
    18.                 }else
    19.                 {
    20. ...
    21. fs?.Dispose();
    22. }
     
  6. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,383
    @justtime

    Here's what i'm thought about:
    Code (CSharp):
    1.  
    2. var request = new HTTPRequest(new Uri(url), OnRequestFinished);
    3.  
    4. request.OnDownloadProgress = (req, down, length) => Debug.LogFormat("{0}", down / (float)length);
    5. request.OnStreamingData += OnData;
    6.  
    7. request.StreamFragmentSize = 1024 * 1024;
    8.  
    9. request.Send();
    10.  
    11. private bool OnData(HTTPRequest req, HTTPResponse resp, byte[] dataFragment, int dataFragmentLength)
    12. {
    13.     if (resp.IsSuccess)
    14.     {
    15.         var fs = req.Tag as System.IO.FileStream;
    16.         if (fs == null)
    17.             req.Tag = fs = new System.IO.FileStream("fileName", System.IO.FileMode.Create);
    18.  
    19.         fs.Write(dataFragment, 0, dataFragmentLength);
    20.     }
    21.  
    22.     // Return true if dataFrament is processed so the plugin can recycle the byte[]
    23.     return true;
    24. }
    25.  
    26. private void OnRequestFinished(HTTPRequest req, HTTPResponse resp)
    27. {
    28.     var fs = req.Tag as System.IO.FileStream;
    29.     if (fs != null)
    30.         fs.Dispose();
    31.  
    32.     switch (req.State)
    33.     {
    34.         // The request finished without any problem.
    35.         case HTTPRequestStates.Finished:
    36.             if (resp.IsSuccess)
    37.             {
    38.                 Debug.Log("Done!");
    39.             }
    40.             else
    41.             {
    42.                 Debug.LogWarning(string.Format("Request finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
    43.                                                 resp.StatusCode,
    44.                                                 resp.Message,
    45.                                                 resp.DataAsText));
    46.             }
    47.             break;
    48.  
    49.         default:
    50.             {
    51.                 // There were an error while downloading the content.
    52.                 // The incomplete file should be deleted.
    53.                 System.IO.File.Delete("filename");
    54.             }
    55.             break;
    56.     }
    57. }
     
    Cromfeli likes this.
  7. soraphol

    soraphol

    Joined:
    May 8, 2018
    Posts:
    1
    Hello BestHTTP,

    Currently, I am using UnityWebRequest to download Csv files and asset bundles from a remote server. However, it seems that UnityWebRequest might not work properly for some Android devices from certain countries such as India and Pakistan. A lot of users are facing "Cannot resolve destination host" error; thus, I am migrating to BestHTTP. After doing some research, I still cannot find an alternative way to get asset bundle except via UnityWebRequest or WWW. Is there anyway to download asset bundle using BestHTTP instead of standard Unity's methods? Thank you.
     
  8. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,383
    @soraphol

    You can use the downloaded raw bytes to create an asset bundle:
    Code (CSharp):
    1. // Start creating the downloaded asset bundle
    2. AssetBundleCreateRequest async =
    3. #if UNITY_5_3_OR_NEWER
    4.     AssetBundle.LoadFromMemoryAsync(request.Response.Data);
    5. #else
    6.     AssetBundle.CreateFromMemory(request.Response.Data);
    7. #endif
    8.  
    9. // wait for it
    10. yield return async;
    11.  
    12. BestHTTP.PlatformSupport.Memory.BufferPool.Release(request.Response.Data);
    13.  
    14. // And process the bundle
    15. yield return StartCoroutine(ProcessAssetBundle(async.assetBundle));
    (From my AssetBundleSample)
     
    soraphol likes this.
  9. justtime

    justtime

    Joined:
    Oct 6, 2013
    Posts:
    337
    Hi! But i replace Unity methods to BestHTTP can i use Caching.IsVersionCached for asset bundle? Or i have to write my own cache it this case, and if so, could you give an advice how to properly make it?
     
  10. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,383
    @justtime

    If the server sends the proper caching headers, the plugin will store the content locally and serve it from there. There's no IsVersionCached, as for the plugin all content are equal it will validate only the headers when a request is sent out. Also, caching is transparent, the very same code can be used and the plugin downloads, update, validates content.
     
    justtime likes this.
  11. justtime

    justtime

    Joined:
    Oct 6, 2013
    Posts:
    337
    What if want to pass "fileName" like a param, not a global var, can i use something like Tag? And should i Dispose resp when Finished?
     
    Last edited: Nov 29, 2019
  12. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,383
    @justtime

    You can add anything to the Tag property, the plugin doesn't uses it. It's just there for user code to pass any information with the request to its callbacks.
    You can modify the previous code to something like this:
    Code (CSharp):
    1. public sealed class DownloadTask
    2. {
    3.     public string Url;
    4.     public string FileName;
    5.     public System.IO.FileStream Stream;
    6.  
    7.     public Action<DownloadTask> Callback;
    8.  
    9.     // add fields as required
    10.  
    11. }
    12.  
    13. var task = new DownloadTask { Url = "...", FileName = "..." };
    14. task.Callback = t => Debug.LogFormat("Task '{0}' is done!", t.FileName);
    15.  
    16. var request = new HTTPRequest(new Uri(task.Url), OnRequestFinished);
    17.  
    18. request.OnDownloadProgress = (req, down, length) => Debug.LogFormat("{0}", down / (float)length);
    19. request.OnStreamingData += OnData;
    20.  
    21. request.StreamFragmentSize = 1024 * 1024;
    22.  
    23. request.Tag = task;
    24.  
    25. request.Send();
    26.      
    27. private bool OnData(HTTPRequest req, HTTPResponse resp, byte[] dataFragment, int dataFragmentLength)
    28. {
    29.     if (resp.IsSuccess)
    30.     {
    31.         var task = req.Tag as DownloadTask;
    32.         if (task.Stream == null)
    33.             task.Stream = new System.IO.FileStream(task.FileName, System.IO.FileMode.Create);
    34.  
    35.         task.Stream.Write(dataFragment, 0, dataFragmentLength);
    36.     }
    37.  
    38.     // Return true if dataFrament is processed so the plugin can recycle the byte[]
    39.     return true;
    40. }
    41.  
    42. private void OnRequestFinished(HTTPRequest req, HTTPResponse resp)
    43. {
    44.     var task = req.Tag as DownloadTask;
    45.     if (task.Stream != null)
    46.         task.Stream.Dispose();
    47.  
    48.     switch (req.State)
    49.     {
    50.         // The request finished without any problem.
    51.         case HTTPRequestStates.Finished:
    52.             if (resp.IsSuccess)
    53.             {
    54.                 if (task.Callback != null)
    55.                     task.Callback(task);
    56.             }
    57.             else
    58.             {
    59.                 Debug.LogWarning(string.Format("Request finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
    60.                                                 resp.StatusCode,
    61.                                                 resp.Message,
    62.                                                 resp.DataAsText));
    63.             }
    64.             break;
    65.  
    66.         default:
    67.             {
    68.                 // There were an error while downloading the content.
    69.                 // The incomplete file should be deleted.
    70.                 System.IO.File.Delete(task.FileName);
    71.             }
    72.             break;
    73.     }
    74. }
     
    justtime likes this.
  13. cgklutts

    cgklutts

    Joined:
    Jun 3, 2014
    Posts:
    8
    [637108008029818998] Ex [PollingTransport]: ParseResponse - Message: 1: Non-negative number required.

    Can't get this to work even in a simplistic form. What would cause this error?
     
  14. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,383
  15. cgklutts

    cgklutts

    Joined:
    Jun 3, 2014
    Posts:
    8
  16. wechat_os_Qy04EV9MQdFdFRket_80b8dn4

    wechat_os_Qy04EV9MQdFdFRket_80b8dn4

    Joined:
    Tuesday
    Posts:
    1
    @BestHTTP
    hi, i need help



    An error occured: Request Finished with Error! Exception: TCP Stream closed unexpectedly by the remote server at BestHTTP.WebSocket.Frames.WebSocketFrame.Fragment (System.UInt16 maxFragmentSize) [0x00000] in <00000000000000000000000000000000>:0

    at BestHTTP.WebSocket.Frames.WebSocketFrame.Fragment (System.UInt16 maxFragmentSize) [0x00000] in <00000000000000000000000000000000>:0

    at BestHTTP.WebSocket.WebSocketResponse.ReceiveThreadFunc () [0x00000] in <00000000000000000000000000000000>:0

    at System.Threading.Tasks.Task.Execute () [0x00000] in <00000000000000000000000000000000>:0

    at System.Threading.ExecutionContext.RunInternal (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state, System.Boolean preserveSyncCtx) [0x00000] in <00000000000000000000000000000000>:0

    at System.Threading.Tasks.Task.ExecuteWithThreadLocal (System.Threading.Tasks.Task& currentTaskSlot) [0x00000] in <00000000000000000000000000000000>:0

    at System.Threading.Tasks.Task.ExecuteEntry (System.Boolean bPreventDoubleExecution) [0x00000] in <00000000000000000000000000000000>:0

    at System.Threading.ThreadHelper.ThreadStart_Context (System.Object state) [0x00000] in <00000000000000000000000000000000>:0

    at System.Threading.ExecutionContext.RunInternal (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state, System.Boolean preserveSyncCtx) [0x00000] in <00000000000000000000000000000000>:0 , Status_Logined

    Stacktrace is not supported on this platform.

    (Filename: ./Runtime/Export/Debug.bindings.h Line: 45)


    When this happened, it like the httprequest thread is down, all the http request will get the Abort State, i try to read the source, but i can't find the reason, please help me
     
  17. Prodigga

    Prodigga

    Joined:
    Apr 13, 2011
    Posts:
    790
    Hi there, we're using besthttp + socket io to communicate with our 'social' server. (Heroku hosted). The game also supports multiplayer via photon. Our socket io connection is very shakey. It constantly drops out and has to reconnect. We know it has nothing to do with the users internet connection because in the middle of a live multiplayer game the socket connection to our social servers will be dropped and have to reconnect while the live photon game continues just fine. This happens multiple times per play session. Is there anything we can do to make our connection more robust? We thought maybe device hitches were causing disconnections so we made BestHTTP run threaded in the background but that hasn't helped. Our timeout is set to 10 seconds on the socket manager which is a very long time for the connection to stall while the game is clearly connected to the internet.
     
  18. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,383
  19. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,383