Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    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,537
    @stonstad

    I have a fix for that somewhere(found it, attached), but threading support is still flagged as experiemental even on 2020.1 and the plugin can't detect whether threading is enabled or not.

    You have to overwrite the old jslib files in the \Best HTTP\Plugins\WebGL\ folder from the zip i attached.
     

    Attached Files:

  2. stonstad

    stonstad

    Joined:
    Jan 19, 2018
    Posts:
    231
    @BestHTTP Re: HTTP Post w/ WASM w/ Threading. Thank you for the fix!
     
  3. Mandelboxed

    Mandelboxed

    Joined:
    Apr 17, 2015
    Posts:
    47
    Hi. I'm using BestHTTP for a Unity based Android application and am running into a strange issue.

    My app works for most users, but for some, the app cannot reach a key server until they reset their router.

    Any idea what could cause this?
     
  4. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,537
    @Mandelboxed Without logs i can't say too much.
    However, i saw a few times that routers intercepted and redirected requests to their internal webserver. These were temporal however, but using HTTPS usually solved these.
     
  5. Mandelboxed

    Mandelboxed

    Joined:
    Apr 17, 2015
    Posts:
    47
    @BestHTTP

    We are using https. Logs below. Any help would be much appreciated.

    Exception:
    SocketException: Could not resolve host 'maps.googleapis.com'

    Code (CSharp):
    1. (wrapper delegate-end-invoke) <Module>.end_invoke_IPAddress[]__this___IAsyncResult(System.IAsyncResult)
    2. System.Net.Dns.EndGetHostAddresses (System.IAsyncResult asyncResult) (at <245cba593bdc463bacb144cf356a8b4b>:0)
    3. BestHTTP.PlatformSupport.TcpClient.General.TcpClient.Connect (System.String hostname, System.Int32 port) (at <0208a0e1686d43058a2582863e2c0ddb>:0)
    4. BestHTTP.HTTPConnection.Connect () (at <0208a0e1686d43058a2582863e2c0ddb>:0)
    5. BestHTTP.HTTPConnection.ThreadFunc (System.Object param) (at <0208a0e1686d43058a2582863e2c0ddb>:0)
    6. UnityEngine.Debug:LogException(Exception)
    7. <>c__DisplayClass18_0:<GetMapData>b__0(HTTPRequest, HTTPResponse)
    8. BestHTTP.HTTPRequest:CallCallback()
    9. BestHTTP.ConnectionBase:HandleCallback()
    10. BestHTTP.HTTPManager:OnUpdate()
    11. BestHTTP.HTTPUpdateDelegator:Update()
    12.  
     
  6. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,537
    @Mandelboxed

    This happens before the TLS negotiation so it could happen with non-HTTPS too. The error is what it says, the DNS service could not resolve host 'maps.googleapis.com' so it can't return with IP addresses the plugin would try to connect.

    As a possible workaround you can try to set ConnectTimeout to 0, that way different code path going to be execcuted:
    Code (CSharp):
    1. HTTPManager.ConnectTimeout = TimeSpan.Zero;
     
  7. Mandelboxed

    Mandelboxed

    Joined:
    Apr 17, 2015
    Posts:
    47
    This is occuring in a live application, are there risks to setting the timeout to zero? What does this do?
     
  8. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,537
    @Mandelboxed

    In a few cases in the past it could solve DNS issues. However, setting the ConnectTimout to zero, it's disables it.

    As DNS querying is done by the runtime (delegating it to the underlying system), the plugin can't really do anything more about it.
     
  9. Mandelboxed

    Mandelboxed

    Joined:
    Apr 17, 2015
    Posts:
    47
    Ok, it might be worth mentioning that only BestHTTP seems to have this problem, UnityWebRequests do not appear to be failing for these same users.

    The problem also appears to occur for some users only after application or OS updates (Android)

    Thanks for your help.
     
  10. econt

    econt

    Joined:
    Apr 8, 2019
    Posts:
    43
    Hi,

    I have a problem my server and client are not connecting locally. I tried different ports e.g. 3000 and 5050. I also tried with my local IPv4 Adress - I made a server in python for socketio and want to connet to unity. I also tried a node.js sserver. It was not possible to connect. I am using Unity 2019.7.4f1 and win10. - I expect that socketio is throwing a debug.log on the connecting event. - What could be the solution?

    Here is the Python code for the server:

    import socket
    import threading
    HEADER = 64
    PORT = 5050
    SERVER = socket.gethostbyname(socket.gethostname())
    ADDR = (SERVER, PORT)
    FORMAT = 'utf-8'
    DISCONNECT_MESSAGE = "!DISCONNECT"
    print ('ip: ' +SERVER)
    server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    server.bind(ADDR)
    def handle_client (conn, addr):
    print(f"[NEW CONNECTION] {addr} connected.")
    Connected = True
    while connected:
    msg_length = conn.recv(HEADER).decode(FORMAT)
    if msg_length:
    msg_length = int(msg_length)
    msg = conn.recv(msg_length).decode(FORMAT)

    if msg == DISCONNECT_MESSAGE:
    connected = False
    print(f"[{addr}] {msg}")
    conn.send("Msg received".encode(FORMAT))
    conn.close()
    def start():
    server.listen()
    print (f"[LISTENING] Server is Listening on {SERVER}")
    while True:
    conn, addr = server.accept()
    thread = threading.Thread(target=handle_client, args=(conn,addr))
    thread.start()
    print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")

    print("[STARTING] server is starting...")
    start()


    Here is the client C#-code in Unity:
    using UnityEngine;
    using System;
    using BestHTTP.SocketIO;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.IO;
    using System.Collections.Generic;
    using System.Dynamic;
    public class EG_socketIOClient : MonoBehaviour
    {
    public Uri URL;
    public String url_string;
    private SocketManager manager;
    // private const string WSGateway = "wss://***/socket.io/";
    void Start()
    {
    SocketOptions options = new SocketOptions();
    options.AutoConnect = true;
    options.ConnectWith = BestHTTP.SocketIO.Transports.TransportTypes.WebSocket;
    manager = new SocketManager(new Uri(url_string), options);
    manager.Socket.On(SocketIOEventTypes.Connect, OnServerConnect);
    manager.Socket.On(SocketIOEventTypes.Disconnect, OnServerDisconnect);
    manager.Socket.On("close", OnClose);
    manager.Open();
    Debug.Log("Manager started");



    }
    void OnDestroy()
    {
    manager.Close();
    }
    void OnServerConnect(Socket socket, Packet packet, params object[] args)
    {
    Debug.Log("Connected");
    }
    void OnServerDisconnect(Socket socket, Packet packet, params object[] args)
    {
    Debug.Log("Disconnected");
    }
    void OnClose(Socket socket, Packet packet, params object[] args)
    {
    Debug.Log("Event received");
    }
    }
     
  11. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,537
    @Mandelboxed

    The plugin uses Dns.BeginGetHostAddresses when ConnectTimeout is non-zero, and Dns.GetHostAddresses for zero.
    I don't know how i could use this one API call so wrong that it couldn't resolve a host only for some users untl they update the app or their OS. For now my only suspect is that an implementation outside and below the plugin.
     
  12. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,537
    @econt Unfortunately, you have a (tcp) socket server instead of a Socket.IO server. The plugin can connect to the latter only.
     
  13. econt

    econt

    Joined:
    Apr 8, 2019
    Posts:
    43
    thanks for your fast response. - I tried now a new server with Socket.IO. But the client in Unity Editor does not seem to get the connection and throw a debug.log. What could be the solution?

    the server seems to accept the client but gives out a error:
    (24992) wsgi starting up on http://0.0.0.0:5000
    (24992) accepted ('169.xxx.xxx.xx', 55375)
    169.xxx.xxx.xx - - [24/Aug/2020 09:15:50] "GET /?EIO=4&transport=websocket HTTP/1.1" 404 117 0.000000


    python server script using socketio

    import eventlet
    import socketio
    sio = socketio.Server()
    app = socketio.WSGIApp(sio, static_files={
    '/': {'content_type': 'text/html', 'filename': 'index.html'}
    })
    @sio.event
    def connect(sio, environ):
    print('connect ', sid)
    @sio.event
    def my_message(sid, data):
    print('message ', data)
    @sio.event
    def disconnect(sid):
    print('disconnect ', sid)
    if __name__ == '__main__':
    eventlet.wsgi.server(eventlet.listen(('', 5000)), app)
     
  14. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,537
  15. econt

    econt

    Joined:
    Apr 8, 2019
    Posts:
    43
  16. econt

    econt

    Joined:
    Apr 8, 2019
    Posts:
    43
    New problem. - I built the client-scene which was connecting to the server in the Unity-Editor for WebGL. - Now there is the problem that the server gives out the message that it accepted the connection. But the client is not connecting only in WebGL.

    What could be the solution?

    The WebGL build runs locally in the firefox browser. - file:///C:/Users/xxx/Desktop/Builds/xxx_best_HTTP_IO/index.html

    The URL of the client is setup on the local ip http://169.xxx.xxx.xx:5000/socket.io/ - and the connection works in the editor. It contains: /socket.io/



    Client scene:
    Gives out some Event_Msges in a Textmesh (in Editor the connection works):
    using UnityEngine;
    using System;
    using BestHTTP.SocketIO;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.IO;
    using System.Collections.Generic;
    using System.Dynamic;
    using TMPro;
    public class EG_socketIOClient : MonoBehaviour
    {
    public Uri URL;
    public String url_string;
    private SocketManager manager;
    private const string WSGateway = "wss://***/socket.io/";
    public TextMeshProUGUI _textmesh;
    void Start()
    {
    SocketOptions options = new SocketOptions();
    options.AutoConnect = true;
    options.ConnectWith = BestHTTP.SocketIO.Transports.TransportTypes.WebSocket;
    manager = new SocketManager(new Uri(url_string), options);
    manager.Socket.On(SocketIOEventTypes.Connect, OnServerConnect);
    manager.Socket.On(SocketIOEventTypes.Disconnect, OnServerDisconnect);
    manager.Socket.On("close", OnClose);
    manager.Socket.On("close", OnClose);

    manager.Open();
    Debug.Log("Manager started");
    Socket nsp = manager.GetSocket("/socket.io");

    // send a message to the client
    }
    private void Update()
    {
    manager.Socket.On("new_message", OnGetMessage);
    }
    void OnDestroy()
    {
    manager.Close();
    }
    //EG neue funktion
    void OnGetMessage(Socket socket, Packet packet, params object[] args)
    {
    Debug.Log("new message");
    _textmesh.text = "new_message";
    }
    void OnServerConnect(Socket socket, Packet packet, params object[] args)
    {
    Debug.Log("Connected");
    _textmesh.text = "connect";
    manager.Socket.Emit("my_message", "hello from Unity");
    }
    void OnServerDisconnect(Socket socket, Packet packet, params object[] args)
    {
    Debug.Log("Disconnected");
    _textmesh.text = "Disconneted";
    }
    void OnClose(Socket socket, Packet packet, params object[] args)
    {
    Debug.Log("Event received");
    _textmesh.text = "Event Received";
    }
    }

    Server Message:
    (24456) accepted ('169.xxx.xxx.xx', 50371)
    169.xxx.xxx.xx - - [25/Aug/2020 07:38:38] "GET /socket.io/?EIO=4&transport=websocket HTTP/1.1" 400 122 0.000000
    The port is always changing on every accept.


    Server-code:

    using UnityEngine;
    using System;
    using BestHTTP.SocketIO;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.IO;
    using System.Collections.Generic;
    using System.Dynamic;
    using TMPro;
    public class EG_socketIOClient : MonoBehaviour
    {
    public Uri URL;
    public String url_string;
    private SocketManager manager;
    private const string WSGateway = "wss://***/socket.io/";
    public TextMeshProUGUI _textmesh;
    void Start()
    {
    SocketOptions options = new SocketOptions();
    options.AutoConnect = true;
    options.ConnectWith = BestHTTP.SocketIO.Transports.TransportTypes.WebSocket;

    manager = new SocketManager(new Uri(url_string), options);
    manager.Socket.On(SocketIOEventTypes.Connect, OnServerConnect);
    manager.Socket.On(SocketIOEventTypes.Disconnect, OnServerDisconnect);
    manager.Socket.On("close", OnClose);
    manager.Socket.On("close", OnClose);

    manager.Open();
    Debug.Log("Manager started");
    Socket nsp = manager.GetSocket("/socket.io");

    // send a message to the client
    }
    private void Update()
    {
    manager.Socket.On("new_message", OnGetMessage);
    }
    void OnDestroy()
    {
    manager.Close();
    }
    //EG neue funktion
    void OnGetMessage(Socket socket, Packet packet, params object[] args)
    {
    Debug.Log("new message");
    _textmesh.text = "new_message";
    }
    void OnServerConnect(Socket socket, Packet packet, params object[] args)
    {
    Debug.Log("Connected");
    _textmesh.text = "connect";
    manager.Socket.Emit("my_message", "hello from Unity");
    }
    void OnServerDisconnect(Socket socket, Packet packet, params object[] args)
    {
    Debug.Log("Disconnected");
    _textmesh.text = "Disconneted";
    }
    void OnClose(Socket socket, Packet packet, params object[] args)
    {
    Debug.Log("Event received");
    _textmesh.text = "Event Received";
    }
    }
     
  17. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,537
    @econt

    I'm a little confused. First you write that "client is not connecting only in WebGL" then later that "the connection works in the editor".

    Also, you subscribe to a socket.io-event in the Update event:
    Code (CSharp):
    1. private void Update()
    2. {
    3.     manager.Socket.On("new_message", OnGetMessage);
    4. }
    It should be enough once in the Start method.

    You can set the plugin's log level to All and send the produced log to my email address (besthttp@gmail.com), from the logs i'm going to know what's really going on.
     
  18. econt

    econt

    Joined:
    Apr 8, 2019
    Posts:
    43

    sorry for the confusion - client is not connecting in WebGL but the client is connecting in the editor. - I will send you the logs via email.

    I deleted " manager.Socket.On("new_message", OnGetMessage);" from update it doesnt make a difference.
     
  19. yuliyF

    yuliyF

    Joined:
    Nov 15, 2012
    Posts:
    152
    Hi, I'm using a standart UnityWebRequest:

    Code (CSharp):
    1. while(!exit) {
    2.             var www = UnityWebRequest.Post(url, form);
    3.             www.certificateHandler = new CertHandler(); // https
    4.             www.timeout = 5;
    5.             yield return www.SendWebRequest();
    6.  
    7.             if(www.isNetworkError || www.isHttpError)
    8.             {
    9.                 Debug.Log(www.error);
    10.             }
    11.             else if (www.downloadHandler.text.Length > 0)
    12.             {
    13.                 exit = true;
    14.                 funcAction(www.downloadHandler.text);
    15.             }
    16.             www.Dispose();
    17.         }
    Is Best HTTP will be better? And Why?
     
  20. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,537
    @econt

    Subscribing to an event in an Update function wouldn't cause an issue like this, but it adds a new entry to the subscription list, and when you receive one "new_message" event, it will dispatch it for every entry.
    Also, it's going to eat up your memory very quickly.
     
  21. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,537
    @yuliyF

    For simple cases like this, Unity's web request can be good and enough.
    With the plugin however, you have more choice on how you want to use it. You can use the same way yield returning on the request object, you can use callbacks or even async-await.
    In general, you have more control over everything, don't have to wait for a new unity release for bug fixes or improvements and you can use new features on older unity versions too.
    Proper caching, you can debug easily your request through a proxy, http/2, connection pooling, etc.

    Down side is that writing a certification validator can be trickier when using the default BouncyCastle TLS handler. Download and upload speed of the BC tls handler also worse, but i'm working on it right now, and download speed getting on pair with my browser and i'm working speeding up upload speed too.
     
  22. Shankar-Ganesh

    Shankar-Ganesh

    Joined:
    Sep 23, 2013
    Posts:
    24
    We are using V2.1.0 and we are getting below issue in iOS TestFlight. But running through Xcode I can't able to see this issue. Can you please let me know is it because of synchronous network calls are running in Main Thread.

    https://stackoverflow.com/questions...esolve-exc-crash-sigkill-for-apple-submission

    Exception Type: EXC_CRASH (SIGKILL)
    Exception Codes: 0x0000000000000000, 0x0000000000000000
    Exception Note: EXC_CORPSE_NOTIFY
    Termination Reason: Namespace SPRINGBOARD, Code 0x8badf00d
    Termination Description: SPRINGBOARD, process-exit watchdog transgression: application<com.companyname.appname>:1285 exhausted real (wall clock) time allowance of 5.00 seconds | ProcessVisibility: Background | ProcessState: Running | WatchdogEvent: process-exit | WatchdogVisibility: Background | WatchdogCPUStatistics: ( | "Elapsed total CPU time (seconds): 2.130 (user 2.130, system 0.000), 21% CPU", | "Elapsed application CPU time (seconds): 0.415, 4% CPU" | )
    Triggered by Thread: 0
     
  23. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,537
  24. Shankar-Ganesh

    Shankar-Ganesh

    Joined:
    Sep 23, 2013
    Posts:
    24
    Ok. Thanks for your reply
     
  25. PixelBoot

    PixelBoot

    Joined:
    Feb 5, 2020
    Posts:
    1
    Hey!
    I'm using Unity 2020.1.

    For some reason if it takes over x seconds between HTTP calls(something like 2 seconds) I get the following message:

    "Remote server closed the connection before sending response header! previous request state: processing. connection state: processing"

    It should be noted that this error only happens to me from Unity Editor! if I make HTTP calls from "Postman", no matter how much time passes between HTTP Calls everything works great...

    Thanks for your help!
     
  26. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,537
    @PixelBoot

    That's probably because the plugin keeps the TCP connection and tries to reuse it. However, because not all servers are informing the client when it's going to close the connection and the server might use lower values, the client will try to use the connection and fail. You can try to set a lower value for HTTPManager.MaxConnectionIdleTime, or even disable connection pooling by setting HTTPManager.KeepAliveDefaultValue to false.
     
  27. conan1987

    conan1987

    Joined:
    Apr 8, 2016
    Posts:
    29
    Thanks very much for helping Tivadar , it is a great asset and a great support
     
  28. econt

    econt

    Joined:
    Apr 8, 2019
    Posts:
    43
    Hi,

    I am trying to make a HTTP Request from a WebGL Client to a InfluxDB. The Requests (GET and POST) work from the Unity-Editor but not from the Browser running WebGL (tested on Chrome and Firefox).

    HTTPRequest request = new HTTPRequest(new Uri("http://127.0.0.1:8086/query?q=show+databases"), OnRequestFinishedGET);
    request.Send();

    HTTPRequest request = new HTTPRequest(new Uri("http://127.0.0.1:8086/query?q=show+databases"), HTTPMethods.Post, OnRequestFinishedPOST);
    request.Send();

    The problem is that the query is overwritten from WebGL, the "+" becomes "%2B" which the server is not able to read as a normal query. It expects a "+" in the syntax.

    "GET /query?q=show%2Bdatabases HTTP/1.1" 400 223 " (Sent and overwritten by the browser)
    "POST /query?q=show%2Bdatabases HTTP/1.1" 400 223 " (Sent and overwritten by the browser)

    How can I send the query so that it is not changed by the WebGL/Browser - what could be the solution?

    Thanks in Advance!
     
  29. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,537
    @econt

    Sent a new jslib to test in a private message.
     
  30. ruenor

    ruenor

    Joined:
    Jun 28, 2013
    Posts:
    6
    Hey!

    This library is very handy but takes a lot of space and I don't want to spend that much space for a network library. Even after I use BESTHTTP_DISABLE_ALTERNATE_SSL, It takes about 2.5 MB space on Android (il2cpp build). Is there any way that I can reduce this disk usage on builds, maybe by deleting some unnecessary protocols for my target platforms?

    My project currently supports Android and iOS platforms. Can you suggest anything?

    Thanks!
     
  31. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,537
    ozgur_unity595 likes this.
  32. dpmontes

    dpmontes

    Joined:
    Dec 7, 2018
    Posts:
    10
    Hello, I'm trying to track down some large spikes in my framerate and I looked at one such spike and it looks like HTTPUpdateDelegator.Update() is taking 324 ms to process. Do you have an idea of what is going on inside of this update? It shouldn't be due to receiving a large message in the websocket because that is happening in a separate thread from the main thread.
     

    Attached Files:

  33. dpmontes

    dpmontes

    Joined:
    Dec 7, 2018
    Posts:
    10
    In response to my previous question, it appears that the callbacks when a websocket message is received are not happening in a separate thread at all but rather inside of the main thread. Is this true?
     
  34. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,537
    @dpmontes

    Yes, that's true. The plugin do as much processing (parsing, decomperessing, etc.) on its threads as it can, but calling the callbacks have to been done on Unity's main thread. Otherwise, you would have to do thread synchronization in every callbacks every time when you would want to access/interact with Unity (other than Debug.Log ...).
     
  35. dpmontes

    dpmontes

    Joined:
    Dec 7, 2018
    Posts:
    10
    Ok thanks! I was able to easily create a thread to do what we wanted to do off the main thread. I just didn't realize that when we switched from WebsocketSharp to BestHTTP that there was that difference. So glad that I realized that now and now our app is buttery smooth again! We love your BestHTTP by the way, the secure websockets work great.
     
  36. LR-Developer

    LR-Developer

    Joined:
    May 5, 2017
    Posts:
    98
    Hello,

    I have a C# host project with DotNet Core 2.1 DLL (with own datatypes) for communication with the unity client it starts.

    Works like a charm as long as I use a string in the messages only, but when I use the DLL with own datatypes I still can receive messages in unity but the parameters are null (Ping is working well still).

    I guess this is because of serialization with System.Text.Json.dll? I tried to copy the Json dll from my C# into my unity plugin folder, but still the problem remains.

    Any idea how I can get my serialization working between my C# host and my unity client?

    The connection is working well, created like this in unity:

    Code (CSharp):
    1.         private void OnRequestFinished(HTTPRequest request, HTTPResponse response)
    2.         {
    3.             if (response != null && response.IsSuccess)
    4.             {
    5.                 if (!string.IsNullOrEmpty(response.DataAsText))
    6.                 {
    7.                     Debug.LogWarning("Response: " + response.DataAsText);
    8.                 }
    9.                 else
    10.                 {
    11.                     Debug.LogError("No Response");
    12.                 }
    13.                 _jwtToken = response.DataAsText;
    14.  
    15.                 _signalRClient = new HubConnection(new Uri(_url + ":" + Globals.SignalrCorePort + "/" + _hubName),
    16.                     new JsonProtocol(new LitJsonEncoder()))
    17.                 {
    18.                     AuthenticationProvider = new HeaderAuthenticator(_jwtToken)
    19.                 };
    20.                 _signalRClient.OnMessage += OnMessageReceived;
    21.                 _signalRClient.OnError += OnError;
    22.                 _signalRClient.OnClosed += OnClosed;
    23.                 _signalRClient.OnConnected += OnConnected;
    24.                 _signalRClient.StartConnect();
    25.             }
    26.             else
    27.             {
    28.                 Debug.LogError("Error during jwt token request");
    29.             }
    30.         }
    Thanks!

    Edit: I guess even before the json serializer, something is missing, when I climb up the call stakc, in unity I get this:

    "{\"type\":1,\"target\":\"SendMessageAsync\",\"arguments\":[\"TitanWpfClient\",{\"commandId\":6,\"dataType\":null,\"serializedData\":null}]}"
     
    Last edited: Sep 29, 2020
  37. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,537
    @LR-Developer

    So, am i understand it right, that you have a (shared) dll containing the datatypes you want to serialize. And when you want to send an object whose type is in this dll, it sends null?
     
    LR-Developer likes this.
  38. LR-Developer

    LR-Developer

    Joined:
    May 5, 2017
    Posts:
    98
    I could fix that error by chaning a property in my C# Host.
    It works, when C# Host sends via SignalRCore, I can receive in Unity.

    Now I get the following error, when I try to send a message from Unity to my C# Host:

    [637370665876029625] Ex [HubConnection]: Exception in OnConnected user code! - Message: 1: Could not load file or assembly 'System.Text.Json, Version=4.0.1.2, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. at Titan.Client.Common.Ipc.Messages.IpcChannelMessage`1[T]..ctor (Titan.Client.Common.Ipc.Messages.EIpcCommands commandId,
     
  39. LR-Developer

    LR-Developer

    Joined:
    May 5, 2017
    Posts:
    98
    Yes that was correct. But works now, I just cannot sent from Unity to C# Host now because of that error mentioned above...
     
  40. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,537
    @LR-Developer Unity tries to load the System.Text.Json dll, but it couldn't. I guess an attribute or something in your dll has a reference to a type located in System.Text.Json.dll.
     
    LR-Developer likes this.
  41. LR-Developer

    LR-Developer

    Joined:
    May 5, 2017
    Posts:
    98
    Yes. I tried to get rid of it like this:

    Original DLL from the C# host, the part in the message where it assigns the data:

    Code (CSharp):
    1.         protected virtual void AssignData(object? data)
    2.         {
    3.             if (data != null)
    4.             {
    5.                 DataType = data.GetType().AssemblyQualifiedName;
    6.  
    7.                 var options = new JsonSerializerOptions
    8.                 {
    9.                     WriteIndented = true
    10.                 };
    11.                 SerializedData = JsonSerializer.Serialize(data, data.GetType(), options);
    12.             }
    13.         }
    14.  
    And in unity I made my own class, that is derived from the original class, and try to overwrite AssignData like this:

    Code (CSharp):
    1.         protected override void AssignData(object data)
    2.         {
    3.             if (data != null)
    4.             {
    5.                 DataType = data.GetType().AssemblyQualifiedName;
    6.  
    7.                 //var options = new JsonSerializerOptions
    8.                 //{
    9.                 //    WriteIndented = true
    10.                 //};
    11.                 //SerializedData = JsonSerializer.Serialize(data, data.GetType(), options);
    12.                 SerializedData = JsonUtility.ToJson(data);
    13.             }
    14.         }
    The message is sent by unity, but the C# Host does not receive.

    When C# sends, unity does receive.

    Thanks for helping!
     
    Last edited: Sep 30, 2020
  42. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,537
    @LR-Developer I don't know where and how your c# host uses the AssignData, but i'm sure that the plugin doesn't try to call it.
     
  43. LR-Developer

    LR-Developer

    Joined:
    May 5, 2017
    Posts:
    98
    The above code part is the part of the DLL used by the C# host side where the Data I sent in the SignalRCore message is Serialized, and in Order to avoid System.Text.Json on the unity side, I derived the part on the unity site, and use the below code part in unity to Serialize the object in the message there.

    C# host can send to unity now, but if unity sends the C# host does receive nothing. I believe the serialization is the problem, but do not know how to solve it.... thanks a lot for any ideas!
     
  44. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,537
    @LR-Developer Could you share (in private) your relevant code for both the server and client?
     
  45. bitwiseio

    bitwiseio

    Joined:
    Aug 2, 2020
    Posts:
    3
    @BestHTTP Hello, i need help with your Framework, im using BestHTTP.SocketIO, but after build i get this error in web console:
    Not implemented: Class::FromIl2CppType UnityLoader.js:4:11226
    {"tid":1,"div":"WebSocketTransport","msg":"OnMessage OnPacket","ex": [{"msg": "Attempt to access method 'BestHTTP.SocketIO.ISocket.OnPacket' on type '0\b5�.' failed.", "stack": ""}],"stack":"","ctxs":[],"t":637372391166380000,"ll":"Exception","bh":1} (Filename: ./Runtime/Export/Debug/Debug.bindings.h Line: 35)

    In Unity it's working, but not after the build for WebGL.
     
    Last edited: Oct 2, 2020
  46. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,537
    @bitwiseio That's quite an interesting error message. It should be come from this part of SocketManager.cs@542:
    Code (CSharp):
    1. Socket socket = null;
    2. if (Namespaces.TryGetValue(packet.Namespace, out socket))
    3.     (socket as ISocket).OnPacket(packet);
    This is the only place where an ISocket's OnPacket is called. Namespaces is Dictionary<string, Socket>, so socket must be null or an ISocket with an OnPacket method.

    The "Attempt to access method 'BestHTTP.SocketIO.ISocket.OnPacket' on type '0\b5�.' failed." message suggests that something went wrong with the compilation. Any chance that you have set Managed Stripping Level to Hight?
     
  47. bitwiseio

    bitwiseio

    Joined:
    Aug 2, 2020
    Posts:
    3
    @BestHTTP wow, ty for the fast answer, really nice support.
    i'm currently using socket.io, https and express npm package on server side and sending socket events like that:

    let data = {
    id: 1,
    msg: 'event message',
    };
    io.emit('eventname',data);

    In Unity i'm using:


    public void addSocketEvents(){
    // this.socket is new SocketManager -> Socket
    this.socket.On('eventname',this.onMessage);
    }

    private void onMessage(Socket socket, Packet packet, params object[] args){
    // do some stuff
    }


    The stripping level was set to low.
     
    Last edited: Oct 2, 2020
  48. BestHTTP

    BestHTTP

    Joined:
    Sep 11, 2013
    Posts:
    1,537
    @bitwiseio I see nothing wrong with your code, it's pretty normal on all front. What version of unity are you using? Would it be possible to send me a minimal repro project?
     
    Last edited: Oct 2, 2020
  49. bitwiseio

    bitwiseio

    Joined:
    Aug 2, 2020
    Posts:
    3
    @BestHTTP i'm using 2019.4.11f1, as i created an testproject for you i've seen your framework is working, the problem was my code with some timing problems, but still ty for your help :)
     
    Last edited: Oct 3, 2020
  50. stonstad

    stonstad

    Joined:
    Jan 19, 2018
    Posts:
    231
unityunity