Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Blockcopy incoming websocket data to shared byte array in a WebGL JS Plugin

Discussion in 'Scripting' started by jc_crash, Aug 20, 2019.

  1. jc_crash

    jc_crash

    Joined:
    Jul 30, 2019
    Posts:
    21
    Hi all!

    I have managed to implement a shared byte array between a javascript plugin and C# in a Unity WebGL build.

    We also implement a websocket for communication with a server which is firing binary data (20 byte blobs) of a known format at us. I have implemented the onMessage callback to receive the binary data as follows:

    Code (JavaScript):
    1.  
    2. window.wsclient.onmessage = function(evt) {
    3.             if (evt.data instanceof ArrayBuffer) {
    4.                 for (var i = 0; i < SharedByteArray.length; i++) {
    5.                     SharedByteArray[i] = evt.data[i];
    6.                 }
    7.             }
    8.             SendMessage('SceneManager', 'RecvString', "1");
    9. };
    10.  
    I believe this method will work for transferring the incoming data into the shared byte array, however I am wondering if there is a more efficient "BlockCopy" equivalent rather than having to copy each byte at a time? We are expected potentially quite a lot of data.

    Any help is appreciated,

    Cheers!
     
    Last edited: Aug 20, 2019
  2. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,745
  3. jc_crash

    jc_crash

    Joined:
    Jul 30, 2019
    Posts:
    21
    Hi @palex-nx

    Thanks for the reference. This is good, except how would I copy that into the already initialized shared array? I initialize it in the plugin at runtime based on a byte array passed in from Unity so I cannot simply reassign it to 'buffer.slice(0)'. Is there a way in JS to do something like this:

    Code (JavaScript):
    1. MySharedByteArray[0] = incomingBuffer.slice(0);
    I want to copy it straight into that memory.

    Thanks for your help!