javascriptc#cefsharp

Pass C# float array to Javascript in CefSharp


I am developing in a WPF project and am using CefSharp.wpf to connect to my html/javascript script. The script is locally on my pc. Currently, I have to convert my C# float array to a string, which takes a long time (192ms). It takes this long because the array has a length of over 200000. The main problem is that this Array has to be sent 30 times per Second, with different values each time.

My Idea was to send the pointer to the array location to the website so it can always get the newest version directly, but I have not found a solution yet. Does anyone have an Idea how I can achieve this?


Solution

  • The solution I found was to use a web socket server. For this I used Fleck. C#:

    HttpListener httpListener;
    WebSocketServer webSocketServer;
    List<IWebSocketConnection> connectedSockets = new List<IWebSocketConnection>();
    webSocketServer = new WebSocketServer("ws://127.0.0.1:8181");
    webSocketServer.Start(socket =>
    {
        socket.OnOpen = () =>
        {
            connectedSockets.Add(socket);
            ExampleSendingFloatArray();
        };
        socket.OnClose = () =>
        {
            connectedSockets.Remove(socket);
        };
    });
    private void SendFloatArrayToClients(float[] data)
    {
        using MemoryStream ms = new MemoryStream();
        using BinaryWriter writer = new BinaryWriter(ms);
    
        for(int i = 0; i < data.Length; i++)
        {
            writer.Write(data[i]);
        }
       
        byte[] byteArray = ms.ToArray();
        foreach (var socket in connectedSockets)
        {
            socket.Send(byteArray);
        }
    }
    private void ExampleSendingFloatArray()
    {
        float[] floatArray = new float[217088*3];
        for (int i = 0; i < 30; i++)
        {
            SendFloatArrayToClients(floatArray);
        }
    }
    

    Javascript:

    socket.onmessage = (event) => {
        if (!(event.data instanceof Blob)) {
            return;
        }
    
        const fileReader = new FileReader();
    
        fileReader.onload = () => {
            threeHandler.sensor.pointCloud.UpdateDephtmap(new Float32Array(fileReader.result));
        };
    
        fileReader.readAsArrayBuffer(event.data);
    
    };
        
    

    Using this code, sending the array 30 times per second is possible. This code is not yet optimised. If I find a way to optimize it, I'll update it here.