Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Best HTTP Released

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

  1. ncortesp

    ncortesp

    Joined:
    Oct 28, 2016
    Posts:
    42
    @BestHTTP does this plugin support the last Unity version? I'm using 2018.1.0f2 and I'm having issues.

    Assets/Best HTTP (Pro)/BestHTTP/SignalRCore/HubConnection.cs(281,44): error CS1502: The best overloaded method match for `BestHTTP.SignalRCore.IProtocol.EncodeMessage(Message)' has some invalid arguments
    Assets/Best HTTP (Pro)/BestHTTP/SignalRCore/HubConnection.cs(281,58): error CS1503: Argument `#1' cannot convert `BestHTTP.SignalRCore.Messages.Message' expression to type `Message'
    Assets/Best HTTP (Pro)/BestHTTP/SignalRCore/JsonProtocol.cs(88,29): error CS1061: Type `Message' does not contain a definition for `type' and no extension method `type' of type `Message' could be found. Are you missing an assembly reference?
    Assets/Best HTTP (Pro)/BestHTTP/SignalRCore/Transports/WebsocketTransport.cs(128,42): error CS1502: The best overloaded method match for `BestHTTP.SignalRCore.IProtocol.ParseMessages(string, ref System.Collections.Generic.List<Message>)' has some invalid arguments
    Assets/Best HTTP (Pro)/BestHTTP/SignalRCore/Transports/WebsocketTransport.cs(128,71): error CS1503: Argument `#2' cannot convert `ref System.Collections.Generic.List<BestHTTP.SignalRCore.Messages.Message>' expression to type `ref System.Collections.Generic.List<Message>'
    Assets/Best HTTP (Pro)/BestHTTP/SignalRCore/Transports/WebsocketTransport.cs(154,42): error CS1502: The best overloaded method match for `BestHTTP.SignalRCore.IProtocol.ParseMessages(byte[], ref System.Collections.Generic.List<Message>)' has some invalid arguments
    Assets/Best HTTP (Pro)/BestHTTP/SignalRCore/Transports/WebsocketTransport.cs(154,71): error CS1503: Argument `#2' cannot convert `ref System.Collections.Generic.List<BestHTTP.SignalRCore.Messages.Message>' expression to type `ref System.Collections.Generic.List<Message>'


    Btw, I've seen that sometimes I get randomly disconnected from the SignalR, how can I handle it, I can't find it in the docs. I would not like to force it to disconnect unless I lose my connection.
     
    Last edited: May 17, 2018
  2. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,663
    @icortesp

    I don't know yet why you received that error. But i'm sure not because of the Unity version as I'm developing the plugin on that exact version recently.
     
  3. tsoiro

    tsoiro

    Joined:
    Mar 17, 2018
    Posts:
    2
    I have some issues using Socket.IO on Hololens Emulator.
    • In Unity Editor the app works fine
    • Building for UWP works fine
    • Executing in Emulator works, but no connection to the server can be established
    • Steps:
      • After pressing the button to start the emulator/app, it is mentioned that the projects are out of date (picture below)
    upload_2018-5-19_0-23-33.png
    • After building, the app is deployed properly
    • When the app starts in the Emulator, the output is the following:
      • Exception thrown at 0x77752502 in BestHTTP.exe: Microsoft C++ exception: Il2CppExceptionWrapper at memory location 0x0CBFE8B8.
        Exception thrown at 0x77752502 in BestHTTP.exe: Microsoft C++ exception: Il2CppExceptionWrapper at memory location 0x0CBFE918.
        Exception thrown at 0x77752502 in BestHTTP.exe: Microsoft C++ exception: Il2CppExceptionWrapper at memory location 0x0CBFEA58.
        Exception thrown at 0x77752502 in BestHTTP.exe: Microsoft C++ exception: Il2CppExceptionWrapper at memory location 0x0DFFE514.
        Exception thrown at 0x77752502 in BestHTTP.exe: Microsoft C++ exception: Il2CppExceptionWrapper at memory location 0x0DFFE574.
        Exception thrown at 0x77752502 in BestHTTP.exe: Microsoft C++ exception: Il2CppExceptionWrapper at memory location 0x0DFFE6B4.
    • No communication to the server
    Setup:
    Hololens Emulator is running on HP Omen
    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. using BestHTTP.SocketIO;
    6.  
    7. public class YetAnotherNetworkManager : MonoBehaviour {
    8.     SocketManager manager;
    9.     SocketOptions options;
    10.  
    11.     void Start()
    12.     {
    13.         options = new SocketOptions();
    14.         options.ConnectWith = BestHTTP.SocketIO.Transports.TransportTypes.WebSocket;
    15.  
    16.         manager = new SocketManager(new Uri("ws://localhost:3000/socket.io/"), options);
    17.  
    18.         manager.Socket.On("hello", OnHello);
    19.     }
    20.  
    21.     void OnHello(Socket socket, Packet packet, params object[] args)
    22.     {
    23.         Debug.Log("hello");
    24.     }
    25. }
    Server is running in Node.js on HP Omen
    Code (JavaScript):
    1. var app = require('express')();
    2. var http = require('http').Server(app);
    3. var io = require('socket.io')(http);
    4.  
    5. io.on('connection', function(socket){
    6.   console.log('a user connected');
    7.   socket.on('disconnect', function() {
    8.       console.log('a user disconnected');
    9.   });
    10.  
    11.   socket.emit('hello');
    12. });
    13.  
    14. http.listen(3000, function(){
    15.   console.log('listening on *:3000');
    16. });
    I can not verify that this is only in the Emulator, because I have no Hololens at the moment.
    I already read about some conflicts with the emulator and localhost, but I don't think that this is the issue here.

    Thank you for your support!
     
  4. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,663
    @tsoiro

    If these are the actual codes that you are using, you are trying to connect to the local host on the emulator. While I'm not familiar with the Hololens emulator I suspect that it emulates a whole new device, and in this case its 'localhost' will be a different localhost than the node.js is running.
     
  5. tsoiro

    tsoiro

    Joined:
    Mar 17, 2018
    Posts:
    2
    Yes, that's true. I have moved the server to another device.
    The connection works in Unity Editor, but I get the same errors in Hololens Emulator. No connection can be established. Any suggestions?

    ========= Update =========
    Fixed it by changing to another project, where I added all of the dependencies/libraries of BestHTTP.
    Thanks for your support!
     
    Last edited: May 19, 2018
  6. jGate99

    jGate99

    Joined:
    Oct 22, 2013
    Posts:
    1,928
    @BestHTTP
    UnityWebRequest.GetTexture gets the texture on background thread, is this also true with BestHTTP?
     
  7. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,663
    @AmRafay1

    No, it will create the texture right when you access the DataAsTexture2D property:
    Code (CSharp):
    1. public Texture2D DataAsTexture2D
    2. {
    3.     get
    4.     {
    5.         if (Data == null)
    6.             return null;
    7.  
    8.         if (texture != null)
    9.             return texture;
    10.  
    11.         texture = new Texture2D(0, 0, TextureFormat.ARGB32, false);
    12.         texture.LoadImage(Data);
    13.  
    14.         return texture;
    15.     }
    16. }
     
    jGate99 likes this.
  8. mike-w-barnett

    mike-w-barnett

    Joined:
    Jul 28, 2013
    Posts:
    2
    Trying to use the solutions to build the dlls but running into some problems with WebGL on Unity 5.6.6. Every time I try and build in Unity I get this error:

    error CS1704: An assembly with the same name `BestHTTP' has already been imported. Consider removing one of the references or sign the assembly
    Assets/Plugins/WebGL/BestHTTP.dll (Location of the symbol related to previous error)
    Assets/Plugins/BestHTTP.dll (Location of the symbol related to previous error)


    The "General" assembly by default has "all" selected for platforms for the plugin. If I exclude WebGL it doesn't change the result. If I straight up remove the "General" assembly I just get an error that says "Error building Player because scripts had compiler errors". No problems if I just have the source code in the assets folder. I have tried building the assembly with Visual Studio for Mac and Visual Studio Community 2015.
     
  9. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,663
    @mike-w-barnett

    After you built the dlls, you have to delete the source code of the plugin. Otherwise all the classes will be define twice, once in the dll and once in the original source code.
     
  10. mike-w-barnett

    mike-w-barnett

    Joined:
    Jul 28, 2013
    Posts:
    2
    Should have mentioned I done that. I removed the entire BestHTTP (Pro) folder from the project and pulled the plugin folder back in (with the newly created dlls). The WebGL folder contains all the jslib files that were in the plugins folder from before. One thing that seems a bit odd is the general dll is 1.5 megs where the WebGL dll is only 282k.

    If I use the "general" dll for WebGL then the project will build but socket.io won't connect as I assume you are using some assemblies that don't exist for WebGL.

    Another note, since the code needs to reference the UnityEngine.dll I am pulling it out of the Unity directory and to another folder and linking the reference to that.
     
    Last edited: May 21, 2018
  11. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,663
  12. li76168

    li76168

    Joined:
    Sep 7, 2014
    Posts:
    11
    Hello,
    I want to upload a mp3 file and add one field to auth the user, but request.AddField() and request.AddBinaryData() can't post together, only when I remove request.AddBinaryData(), the field can be received.
     
  13. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,663
    @li76168

    I used the following code to test AddField + AddBinaryData:
    Code (CSharp):
    1. Uri uri = new Uri("http://httpbin.org/post");
    2.  
    3. HTTPRequest request = new HTTPRequest(uri, HTTPMethods.Post, (req, resp) =>
    4. {
    5.     switch (req.State)
    6.     {
    7.         // The request finished without any problem.
    8.         case HTTPRequestStates.Finished:
    9.             if (resp.IsSuccess)
    10.             {
    11.                 Debug.Log("Request Finished Successfully! Response: " + resp.DataAsText);
    12.             }
    13.             else // Internal server error?
    14.                 Debug.LogWarning(string.Format("Request Finished Successfully, but the server sent an error. Status Code: {0}-{1} Message: {2}",
    15.                                                 resp.StatusCode,
    16.                                                 resp.Message,
    17.                                                 resp.DataAsText));
    18.             break;
    19.  
    20.         // The request finished with an unexpected error. The request's Exception property may contain more info about the error.
    21.         case HTTPRequestStates.Error:
    22.             Debug.LogWarning("Request Finished with Error! " + (req.Exception != null ? (req.Exception.Message + "\n" + req.Exception.StackTrace) : "No Exception"));
    23.             break;
    24.  
    25.         // The request aborted, initiated by the user.
    26.         case HTTPRequestStates.Aborted:
    27.             Debug.LogWarning("Request Aborted!");
    28.             break;
    29.  
    30.         // Connecting to the server is timed out.
    31.         case HTTPRequestStates.ConnectionTimedOut:
    32.             Debug.LogError("Connection Timed Out!");
    33.             break;
    34.  
    35.         // The request didn't finished in the given time.
    36.         case HTTPRequestStates.TimedOut:
    37.             Debug.LogError("Processing the request Timed Out!");
    38.             break;
    39.     }
    40. });
    41.  
    42. request.AddBinaryData("myfile", this.tex.EncodeToJPG());
    43. request.AddField("myfield", "myfield value");
    44.  
    45. request.Send();
    It gone through a proxy so could inspect what has been sent and received:
    upload_2018-5-23_17-45-37.png
    (Upper part is what the client sent, lower one is what received.)

    As you can see the client sent both fields, the server received and processed them and sent back all of them successfully.

    Can you send more details how are you trying to send and what server are you using?
     
  14. li76168

    li76168

    Joined:
    Sep 7, 2014
    Posts:
    11
    Hello,
    I found the problem, when I upload to local web server, the field can't be received, but remote web server every will be fine.I don't know why.
     
  15. MS80

    MS80

    Joined:
    Mar 7, 2014
    Posts:
    346
    @BestHTTP Hello and congrats to your promising product!

    I would like to know more about large file download and using cache. Are there some more complete examples / tutorials on how to download large files (*.mp4) and to use them afterwards (f.e unity video player)? Is it possible to download and watch / stream a large video file while downloading (the video should also be cached and be available offline next time)?

    I like the included example scene for it's minimal design, but these are my impressions regarding the http samples (unity 2017.3.0f3 and BestHttp 1.10.5 / 1.10.6 ):
    • outdated UI, there could be examples using the new Unity UI
    • large file download sample does not work (1.10.6): error message 1
    • texture download sample does not work (1.10.6): error message 2
    • large file download sample does not show what to do with the downloaded data. It would be nice to have a sample which shows realistic and typical usage like download of large video files which gets played in the unity video player. How to convert the request data to a Videoclip for videoplayer?
    • caching does not work correctly in texture download and large file download samples (1.10.5), cache files are stored, but after removing internet connection files will not load from cache (texture sample, large file sample with flag "caching disabled = false"): error message 3, 4 (it says all images are loaded from cache, but images do not become visible)
    • sometimes more than one download progress is neccessary until a cache file is created
    • clear cookies does nothing? at least the text info does show existing cookies? (1.10.5)
    error1:
    Request Finished with Error! Es konnte keine Verbindung hergestellt werden, da der Zielcomputer die Verbindung verweigerte.
    at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP, Boolean requireSocketPolicy) [0x00000] in <filename unknown>:0
    at System.Net.Sockets.Socket+Worker.Connect () [0x00000] in <filename unknown>:0
    UnityEngine.Debug:LogError(Object)
    BestHTTP.Examples.LargeFileDownloadSample:<StreamLargeFileTest>m__1(HTTPRequest, HTTPResponse) (at Assets/Best HTTP (Pro)/Examples/HTTP/LargeFileDownloadSample.cs:160)
    BestHTTP.HTTPRequest:CallCallback() (at Assets/Best HTTP (Pro)/BestHTTP/HTTPRequest.cs:1267)
    BestHTTP.ConnectionBase:HandleCallback() (at Assets/Best HTTP (Pro)/BestHTTP/Connections/ConnectionBase.cs:173)
    BestHTTP.HTTPManager:OnUpdate() (at Assets/Best HTTP (Pro)/BestHTTP/HTTPManager.cs:648)
    BestHTTP.HTTPUpdateDelegator:Update() (at Assets/Best HTTP (Pro)/BestHTTP/HTTPUpdateDelegator.cs:178)

    error2:
    Request Finished with Error! Es konnte keine Verbindung hergestellt werden, da der Zielcomputer die Verbindung verweigerte.
    at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP, Boolean requireSocketPolicy) [0x00000] in <filename unknown>:0
    at System.Net.Sockets.Socket+Worker.Connect () [0x00000] in <filename unknown>:0
    UnityEngine.Debug:LogError(Object)
    BestHTTP.Examples.TextureDownloadSample:ImageDownloaded(HTTPRequest, HTTPResponse) (at Assets/Best HTTP (Pro)/Examples/HTTP/TextureDownloadSample.cs:159)
    BestHTTP.HTTPRequest:CallCallback() (at Assets/Best HTTP (Pro)/BestHTTP/HTTPRequest.cs:1267)
    BestHTTP.ConnectionBase:HandleCallback() (at Assets/Best HTTP (Pro)/BestHTTP/Connections/ConnectionBase.cs:173)
    BestHTTP.HTTPManager:OnUpdate() (at Assets/Best HTTP (Pro)/BestHTTP/HTTPManager.cs:648)
    BestHTTP.HTTPUpdateDelegator:Update() (at Assets/Best HTTP (Pro)/BestHTTP/HTTPUpdateDelegator.cs:178)

    error3:
    Request Finished with Error! Could not resolve host 'besthttp.azurewebsites.net'
    at <0x00000 + 0x00000> <unknown method>
    at (wrapper delegate-end-invoke) <Module>:end_invoke_IPAddress[]__this___IAsyncResult (System.IAsyncResult)
    at System.Net.Dns.EndGetHostAddresses (System.IAsyncResult asyncResult) [0x00038] in <2d96311935af40c7b35c6ff5c955d7e7>:0
    at BestHTTP.PlatformSupport.TcpClient.General.TcpClient.Connect (System.String hostname, System.Int32 port) [0x00057] in C:\TEMP_PROJECT\besthttp\Assets\Best HTTP (Pro)\BestHTTP\PlatformSupport\TcpClient\TcpClient.cs:417
    at BestHTTP.HTTPConnection.Connect () [0x0018e] in C:\TEMP_PROJECT\besthttp\Assets\Best HTTP (Pro)\BestHTTP\HTTPConnection.cs:495
    at BestHTTP.HTTPConnection.ThreadFunc (System.Object param) [0x00090] in C:\TEMP_PROJECT\besthttp\Assets\Best HTTP (Pro)\BestHTTP\HTTPConnection.cs:186
    UnityEngine.Debug:LogError(Object)
    BestHTTP.Examples.TextureDownloadSample:ImageDownloaded(HTTPRequest, HTTPResponse) (at Assets/Best HTTP (Pro)/Examples/HTTP/TextureDownloadSample.cs:159)
    BestHTTP.HTTPRequest:CallCallback() (at Assets/Best HTTP (Pro)/BestHTTP/HTTPRequest.cs:1267)
    BestHTTP.ConnectionBase:HandleCallback() (at Assets/Best HTTP (Pro)/BestHTTP/Connections/ConnectionBase.cs:173)
    BestHTTP.HTTPManager:OnUpdate() (at Assets/Best HTTP (Pro)/BestHTTP/HTTPManager.cs:648)
    BestHTTP.HTTPUpdateDelegator:Update() (at Assets/Best HTTP (Pro)/BestHTTP/HTTPUpdateDelegator.cs:178)

    error4:
    Request Finished with Error! Could not resolve host 'file-examples.com'
    at <0x00000 + 0x00000> <unknown method>
    at (wrapper delegate-end-invoke) <Module>:end_invoke_IPAddress[]__this___IAsyncResult (System.IAsyncResult)
    at System.Net.Dns.EndGetHostAddresses (System.IAsyncResult asyncResult) [0x00038] in <2d96311935af40c7b35c6ff5c955d7e7>:0
    at BestHTTP.PlatformSupport.TcpClient.General.TcpClient.Connect (System.String hostname, System.Int32 port) [0x00057] in C:\TEMP_PROJECT\besthttp\Assets\Best HTTP (Pro)\BestHTTP\PlatformSupport\TcpClient\TcpClient.cs:417
    at BestHTTP.HTTPConnection.Connect () [0x0018e] in C:\TEMP_PROJECT\besthttp\Assets\Best HTTP (Pro)\BestHTTP\HTTPConnection.cs:495
    at BestHTTP.HTTPConnection.ThreadFunc (System.Object param) [0x00090] in C:\TEMP_PROJECT\besthttp\Assets\Best HTTP (Pro)\BestHTTP\HTTPConnection.cs:186
    UnityEngine.Debug:LogError(Object)
    BestHTTP.Examples.LargeFileDownloadSample:<StreamLargeFileTest>m__1(HTTPRequest, HTTPResponse) (at Assets/Best HTTP (Pro)/Examples/HTTP/LargeFileDownloadSample.cs:161)
    BestHTTP.HTTPRequest:CallCallback() (at Assets/Best HTTP (Pro)/BestHTTP/HTTPRequest.cs:1267)
    BestHTTP.ConnectionBase:HandleCallback() (at Assets/Best HTTP (Pro)/BestHTTP/Connections/ConnectionBase.cs:173)
    BestHTTP.HTTPManager:OnUpdate() (at Assets/Best HTTP (Pro)/BestHTTP/HTTPManager.cs:648)
    BestHTTP.HTTPUpdateDelegator:Update() (at Assets/Best HTTP (Pro)/BestHTTP/HTTPUpdateDelegator.cs:178)
     
    Last edited: May 23, 2018
  16. Barritico

    Barritico

    Joined:
    Jun 9, 2017
    Posts:
    374
    Hi.

    I have a problem. I have researched hours ... but without success. So let's see if you can help me.

    After an API query the JSON result is as follows, contained in response.DataAsText

    [{\ "IDUSER \": \ "22509ecbc872f133298d214af237319944783a60 \", \ "ZONE \": \ "S1 \", \ "IDTRACK \": 1, \ "S1 \": 1.688388000000000e + 001}]

    After execute the following code:

    object times2 = BestHTTP.JSON.Json.Decode (response.DataAsText);

    The result is the one that appears in the attached image.

    httpbest_1.jpg

    I have read in the forum, and I have put the following code:

    var listdata = BestHTTP.JSON.Json.Decode (response.DataAsText) as List <object>;

    With the same result as in the attached image. And, after:

    var data = BestHTTP.JSON.Json.Decode (listdata [0] as string) as Dictionary <string, object>;

    In this case it gives me a "null" value.

    I can not get the data data by code. I can not assign, for example, the value of the S1 key. In Visual Studio 2017 the error appears:

    "Indexing can not be applied with [] to an expression of type object"

    The fact is that I am totally blocked and I do not know how to continue.

    Thank you very much.

    Unity Version 2017.3.0f3
     
    Last edited: May 24, 2018
  17. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,663
    @MS80

    Thank you for your valuable feedback!

    The UI is but it's written when the main Unity version was around 3.5. Additionally i still receive support requests and purchases for old Unity versions. Until it works on old and newer versions of Unity I have no intention to rewrite these samples.

    Half of the error messages were caused by a bug in the samples other half (Could not resolve host 'xyz'.) are dns errors that i can't reproduce.

    The large file download sample has an ProcessFragments function how the downloaded bytes can be used in the same order as they are downloaded.
    A streamed video playing sample would be nice, but i'm not sure it's possible with unity provided VideoPlayer and VideoClip classes.
    The best approach i can think of would be to save the movie to disk, and after a specified amount start to play that file.

    Caching without internet connection: the plugin does, what the server wants. If the server send the content with caching headers of Age and MaxAge, it will serve the content without internet connections. However if the content is sent with an ETag header (like in the case of the texture download sample), it must check theirs freshness, and this step requires an active internet connection. (If the content is fresh, it will not download it again, and will server it from the locale cache.)

    "sometimes more than one download progress is neccessary until a cache file is created"

    Can you share more details about this? I couldn't reproduce it on my end.

    "clear cookies does nothing? at least the text info does show existing cookies?"

    This was a bug in the sample.
     
  18. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,663
    @Barritico

    You could access your data like this:
    Code (CSharp):
    1. var listdata = BestHTTP.JSON.Json.Decode(response.DataAsText) as List<object>;
    2. var data = listdata[0] as Dictionary<string, object>;
    3. Debug.log(data["IDUSER"]);
    For a json list ("[]") Json.Decode will return a List<object>, and json objects ("{}") will be decoded as Dictionary<string, object>. They can be nested, so in your case, it will decode your json as a list of dictionary.
     
    Last edited: May 25, 2018
    Barritico likes this.
  19. Barritico

    Barritico

    Joined:
    Jun 9, 2017
    Posts:
    374
    Thanks!!!!
    Works fine.
     
  20. MS80

    MS80

    Joined:
    Mar 7, 2014
    Posts:
    346
    Thanks @BestHTTP !

    Somehow I've overlooked the lines in ProcessFragments, saving and playing after dowloading *.mp4 with unity video player works now ;)

    I think play the file while saving it is more complicated, this results in an error:

    Ex [HTTPRequest]: CallCallback - Message: 1: Sharing violation on path C:\Testsave\bigVideoFile.mp4 at System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, System.Int32 bufferSize, System.Boolean anonymous, System.IO.FileOptions options) [0x001d8] in <c95265f74fdf4905bfb0d5a4b652216c>:0 ......

    Also I will have to learn something about ETag header and how to set Age and MaxAge.
     
  21. ivan_barbancic

    ivan_barbancic

    Joined:
    Jul 21, 2015
    Posts:
    3
    Hi,

    I have a problem when downloading large files. On the server I get the error "An existing connection was forcibly closed by the remote host" and I am not sure if this is because of the plugin or the server.
    The file is about 150MB and I am using the streaming option.
    Is there maybe some option to avoid this?
    Thanks.
     
  22. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,663
    @ivan_barbancic

    When streaming is used, the plugin will not use the request's Timeout property (EnableTimeoutForStreaming is false by default). Otherwise it will not try to close the connection.

    You can set the plugin's logging to verbose and send the log to my email address, maybe I can see some clue what's going on:
    Code (CSharp):
    1. BestHTTP.HTTPManager.Logger.Level = BestHTTP.Logger.Loglevels.All;
     
  23. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,663
    @MS80

    This is good write up about caching that i usually link: http://dev.mobify.com/blog/beginners-guide-to-http-cache-headers/

    The plugin can use the following headers for caching:
    • Cache-Control with max-age and must-revalidate params
    • Expires
    • ETag
    And theirs support headers: Last-Modified, Age and Date.
    Of course not all of these headers must present. For example, it can use only an ETag header for caching and re-validating that cache entry.
     
  24. bdovaz

    bdovaz

    Joined:
    Dec 10, 2011
    Posts:
    1,039
    Now that Signal R Core is finally released are we going to have a BestHTTP stable release on this?
     
  25. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,663
    @N3uRo

    Yep, I will start to finalize and extend my implementation.
     
  26. chuyuanzhang

    chuyuanzhang

    Joined:
    May 31, 2018
    Posts:
    3
    Hi I sometimes use Web socket in the game sometimes back crazy output The socket has been down, how do I judge him and reconnect?
     
  27. quevedin

    quevedin

    Joined:
    May 22, 2018
    Posts:
    1
    This support secured websockets and socketio 2?
     
  28. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,663
    @chuyuanzhang

    Can you elaborate more on this? I'm not sure about your issue.
     
  29. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,663
    @quevedin

    Yes, both secure websockets (wss://) and Socket.IO 2 (and newer) are supported.
     
  30. pfleetwood22

    pfleetwood22

    Joined:
    Jun 6, 2016
    Posts:
    28
    I am seeing something curious. I'm using 2017.4.4, and when I run in the editor and use the HTTP OnProgress callback, I get a final update where the downloaded bytes are equal to the length bytes. This is what I expect. However, on device (both Android and iOS) the downloaded bytes are always 183 bytes greater than the length.

    Correction: I see this in the editor as well.

    I can't explain why that would be. In my case, I am downloading data from AWS CloudFront.

    Any ideas? For now, I'm testing the State of the HTTPRequest, and if it is Finished, and downloaded is different than length, I just use the length value for both.

    PS. I am using version 1.10.3 of BestHTTP and the .NET 4.6 runtime in Unity (with IL2CPP for both platforms).

    Update:
    It looks like these extra bytes were caused by having the CDN redirect HTTP to HTTPS. When I support both of them, the extra bytes do not appear.
     
    Last edited: Jun 1, 2018
  31. shb

    shb

    Joined:
    Oct 7, 2012
    Posts:
    23
    Hi, I have a issue with WebGL build under load balanced socket.io servers.

    I have a AWS hosted socket.io server and I want to scale out by putting the servers under AWS ALB(application load balancer). AWS ALB supports load balancing websocket/socket.io servers by enabling stickiness features.
    https://www.reddit.com/r/aws/comments/56xdhk/best_approach_for_socketio_with_aws_alb/

    I set up my own servers using AWS ALB and I have following issue when I try connecting to the server
    through ALB not directly to seperate servers.
    The symptoms are:

    - It works fine on editor and mobile build.
    - It fails to connect (maybe handshake fails?) on WebGL build.
    - I can even connect to my ALB using pure javascript socket.io client (not unity-besthttp powered webgl build).
    - If I put a single server under ALB or connect directly to server not through ALB, the WebGL build works fine.

    I built WebGL build for your information which connect to my ALB by just replacing the url in the besthttp sample chat.

    Here's detailed info you can try.

    * The load balancer url:
    https://bima-slot.pawagame.com/socket.io

    * 2 servers url under ALB :
    https://bima-slot-a01.pawagame.com/socket.io
    https://bima-slot-a02.pawagame.com/socket.io

    Try the sample that I built. (Socekt.io samples Chat >Start Sample) that connects to ALB url, and I get errors.
    http://d1cchznlo2efu4.cloudfront.net/sample/index.html

    blob:http://d1cchznlo2efu4.cloudfront.net/d5e6fea8-38f2-40fb-893a-d08c6ce5724d:2 Error: Code: Internal Message: "Polling - Request finished Successfully, but the server sent an error. Status Code: 400- Message: {"code":1,"message":"Session ID unknown"} Uri: https://bima-slot.pawagame.com/sock...lling&t=3195312859-1&sid=-DZb-bJ-UgsQw1PnAAAV"

    blob:http://d1cchznlo2efu4.cloudfront.net/74130e5e-2b42-49a6-bc1c-ffd7cad2fbd8:2 WebSocket connection to 'wss://bima-slot.pawagame.com/socket.io/?EIO=4&transport=websocket&sid=qXxlwHbnLk7x9HbCAAAY' failed: Error during WebSocket handshake: Unexpected response code: 502
    Screen Shot 2018-06-02 at 12.07.38 PM.png

    I don't think it's ALB issue, because the chat sample works fine on editor and mobile build, and even I can connect to the ALB on my javascript socket.io client.

    Scale out is a must on production environment and I think AWS ALB seems to be the one of the best choice. Can you help to make the WebGL build work?
    BTW, I tried most of the combination of BestHttp(from older to the latest) and Unity(2017-2018), and have same issue.
    Screen Shot 2018-06-02 at 11.44.07 AM.png
     
    Last edited: Jun 2, 2018
  32. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,663
    @pfleetwood22

    The download progress will try to report the expected size of the download and the downloaded bytes. When the server sends a Content-Length header the two should match, otherwise the plugin has no idea what will be the final size (in this case the downloadLength parameter might change between two progress callback).

    Also, the OnProgress callback will report what the plugin downloaded from the server, but if the content is sent compressed, the final bytes will be different.

    OnProgress - downloaded param: raw bytes downloaded from the server without any decompression
    OnProgress - downloadLength param: expected size of the download. It's constant and accurate when Content-Length is present.
    Response's Data property: the downloaded and decompressed bytes.
     
  33. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,663
    @shb

    Thanks for the URLs they were really helpful.

    Your load balancer requires to send back cookies to maintain the sticky feature. Unfortunately the plugin doesn't support cookies in WebGL builds.
    Nonetheless the fix is relatively easy. You can edit the \Best HTTP (Pro)\Plugins\WebGL\BestHTTP_WebRequest.jslib and add the http.withCredentials = true; line just after var http = new XMLHttpRequest();:
    Code (JavaScript):
    1. var http = new XMLHttpRequest();
    2. http.withCredentials = true;

    Alternately, you can try out to connect right with websocket for explicit stickiness:
    Code (CSharp):
    1. SocketOptions options = new SocketOptions();
    2. options.ConnectWith = BestHTTP.SocketIO.Transports.TransportTypes.WebSocket;
    3.  
    4. Manager = new SocketManager(new Uri("https://bima-slot.pawagame.com/socket.io/"), options);
     
  34. shb

    shb

    Joined:
    Oct 7, 2012
    Posts:
    23
    Working like magic!
    Thanks for great support.
     
  35. le_duke

    le_duke

    Joined:
    Aug 30, 2011
    Posts:
    48
    Hi,
    I just bought the asset and I'm pretty happy with it.
    I'm just wondering if there is a way to get the response time of an http request.
    I tried to do it using this code but since the callback is called on the main thread this is inducing error due to frame rate I guess.

    How can I manage to get the real response time ?

    Code (CSharp):
    1.     public float getRequestDuration()
    2.     {
    3.         return (float)(endTime - sentTime).TotalSeconds;
    4.     }
    5.  
    6.     public void sendRequest(Action<OrosDataRequest> doneCallback)
    7.     {
    8.         this.sentTime = DateTime.Now;
    9.  
    10.         this.www = new HTTPRequest(new Uri(this.url), delegate (HTTPRequest httpRequest, HTTPResponse response)
    11.         {
    12.             this.endTime = DateTime.Now;
    13.         });
    14.         this.www.Send();
    15.     }
     
  36. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,663
    @le_duke

    I think this is the best/safest way to measure it.

    The plugin can run in fully threaded mode by calling the following line somewhere in your startup code:
    Code (CSharp):
    1. HTTPUpdateDelegator.IsThreaded = true;
    In this case it would produce better results, but you would have to deal with all the threading stuff.
     
  37. le_duke

    le_duke

    Joined:
    Aug 30, 2011
    Posts:
    48
    Thanks for the answer.
    The only problem with this solution is that the callback is called on the main thread so the value returned by getRequestDuration is impacted by the framerate.

    For example if I set target frame rate with :
    Code (CSharp):
    1. Application.targetFrameRate = 1;
    getRequestDuration() will always return a value > 1.

    Do you have anyway to track this data internaly and directly from the threaded part and return it in the HTTPResponse ?
     
  38. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,663
    @le_duke

    Yes, if you have low framerate it can add quite a lot.

    The best place would be to add it to the HTTPConnection. It already sets a StartTime and in its end of ThreadFunc you can add something like this (HTTPConnection.cs around line 443):
    Code (CSharp):
    1. LastProcessTime = DateTime.UtcNow;
    2.  
    3. CurrentRequest.Duration = this.StartTime - DateTime.UtcNow;
    And a Duration property to the HTTPRequest class:
    Code (CSharp):
    1. public TimeSpan Duration { get; set; }
    After this, duration will be tracked automatically, and you can access it in your callback.
     
  39. le_duke

    le_duke

    Joined:
    Aug 30, 2011
    Posts:
    48
    It seems like this is not executed when data is loaded from cache, so we may have to set duration elsewhere too.
    Code (CSharp):
    1. CurrentRequest.Duration = this.StartTime - DateTime.UtcNow;

    Altough it's working great thanks ! it would be cool if you add it directly to your next release ;)
     
  40. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,663
    @le_duke

    Also, tcp connection time isn't added too (StartTime is set right after Client.Connect). But, you can add a new DateTime field to set and use as it fits better for you.
     
  41. conigliocattivo

    conigliocattivo

    Joined:
    May 14, 2013
    Posts:
    10
    Hello,
    I don't know if this has been reported before but I am trying using these request properties (from the docs):

    request.UseStreaming = true;
    request.StreamFragmentSize = 1 * 1024 * 1024; // 1 megabyte

    and the callback got called every 10 megabytes instead of 1 megabyte. If I change it to 1024 * 102 it got called every megabyte.
    Is it a known bug? I am on Unity 2017.4 & MacOS Sierra.

    Thanks,
    Antonio
     
  42. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,663
    @conigliocattivo

    Is it called with one large (10 Mb) of segment, or with 10 segments 1 Mb each?

    Because there's another setting - MaxFragmentQueueLength - that controls how much fragments the plugin can buffer up.
    But, if framerate is slow and your internet connection is quick, the plugin can fill up the queue quickly and next time you call GetStreamedFragments() it will return with all the fragments (10 in this case).

    You can set the MaxFragmentQueueLength property to 1 and in that case the plugin will fill up only one fragment.
     
  43. conigliocattivo

    conigliocattivo

    Joined:
    May 14, 2013
    Posts:
    10
    Got it! It was indeed downloading 10 fragments of 1 Mb each.

    Thanks!
    Antonio
     
  44. Onutrem

    Onutrem

    Joined:
    Dec 8, 2017
    Posts:
    3
    Hello.

    I am not able to make this asset working in Unity (Windows 10).

    I was looking for the websocket feature and when I launched the SampleSelctor scene and tried to connect to wss://echo.websocket.org or another websocket endpoint, I always ended getting this message :


    Opening Web Socket...
    -WebSocket closed! Code 1000 Message: Closed while opening.


    I tried to edit the WebSocketSample script by checking the state and if the websocket was open just after the call of webSocket.Open() and I got : Connecting and False.

    What could be the issue ?

    Thanks.
     
  45. le_duke

    le_duke

    Joined:
    Aug 30, 2011
    Posts:
    48
    Is it a known issue that requests are slower with BestHTTP than with UnityWebRequests ?
    From my testing loading 100 pngs from my server (in the Unity editor):

    BestHTTP (disabled cache) : ~ 10s
    BestHTTP (enabled cache) : ~ 13s
    UnityWebRequest : ~ 2.5s
     
  46. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,663
    Yep, UnityWebRequest is quicker. It uses the cURL library (on desktop platforms), or native implementation where possible (iOS, Android for example). While for the plugin it has to go through multiple layers and a lot of little overheads will add up (especially if it uses HTTPS).

    The caching one is interesting although, as it should speed up things instead of slowing down. One possible explanation would be if the plugin must revalidate the content and it has to redownload the content. Or it's when you first download all the pngs and the cache is enabled?
     
  47. NanoMath

    NanoMath

    Joined:
    Dec 22, 2012
    Posts:
    33
    Hi

    Thanks for so great asset pack Best HTTP (Pro). I bought it ! I need to make JSON-RPC via HTTP to interact with blockchain BitShares. Is it possible to you Best HTTP (Pro) for JSON-RPC calls ? right ? Can you show me example please how to correctly should I use it with next Uri for example: https://node.testnet.bitshares.eu

    Thank you very much ! I'm waiting your response ...
     
  48. le_duke

    le_duke

    Joined:
    Aug 30, 2011
    Posts:
    48
    @BestHTTP ok I understand that there could be an overhead but 75ms per requests is a lot no ?

    I did more test today and it seems like, the more data there is in the cache the more time takes the requests to return a result. (Tested on Windows and Android same issue).
    Cache size is 45 Mb with ~6k files cached.

    Do you think this issue could be related to your implementation of the cache system ?
     
  49. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,663
    @le_duke

    Is it possible to share your test code with me?

    ~6k entries in the cache seems quite a lot. A cache lookup is just a TryGetValue on a Dictionary, but the plugin will save the cache library after each request, and that can add up and i can imaging that it can be time-consuming with that much entries.
    If you want, you can remove the HTTPCacheService.SaveLibrary(); line in the HTTPConnection.cs, on platforms where OnApplicationQuit is called the plugin will save the cache library, but you can call it manually too.
     
    Last edited: Jun 7, 2018
  50. le_duke

    le_duke

    Joined:
    Aug 30, 2011
    Posts:
    48
    @BestHTTP I'll send you a sample code to show the issue as soon as I can.
    Is there a way to limit the max number of cache entry ?

    When you say the plugin is saving the cache library after each request, you mean you write a file with metadata about all entries each time ? (like path, date of caching etc.)

    Yes but what happen if app crash ? will your code handle it anyway ?

    I'm sorry to say that I bought this plugin to gain time but at the moment this is not very succesful...
    I'm not going to hide from you that I expected better for a plugin at this price.