2

I have Node.js WebSocket server and Unity client with Best HTTP asset. I used to transfer JSON data, but parsing cost too much CPU resources. Now, i try to send byte[] message from C# as follows:

//sending sample array - new float[] { 1.32, 3.12 }
//convert an object to a byte array
private byte[] ObjectToByteArray(Object obj)
{
    if(obj == null)
       return null;

    BinaryFormatter bf = new BinaryFormatter();
    MemoryStream ms = new MemoryStream();
    bf.Serialize(ms, obj);

    return ms.ToArray(); 
}

But server received Uint8Array [1, 3] and fractional part is lost.

var wss = new WebSocket.Server({ port: 8080 });
wss.binaryType = "arraybuffer";
wss.on('connection', function connection(ws) {
    ws.on('message', function (message) {
    });
});

Main question: How to right parse arrays (especially nested arrays) in binary format and encode to array after?

2 Answers2

1

Normal binary serialization can be a bottleneck for Web API's If your objects are well defined and can be modeled into classes, i recommend you use Protobuf.

The great thing is that it's cross platform and you can use the same definition both for your NodeJS server and C# client.

areller
  • 4,800
  • 9
  • 29
  • 57
0

You can try binary json BSON http://bsonspec.org/implementations.html

or MSGPACK http://msgpack.org/index.html

both libraries offer implementation in various languages and are well tested.

Gntem
  • 6,949
  • 2
  • 35
  • 48
  • I read about BSON parser in Node.js, it works much slower than JSON. I need to reduce CPU load on server side when encoding/decoding transfer data - its main target. – Michael Kors Apr 11 '17 at 21:31
  • how come something that was written to be faster in parsing/writing than json is actually slower from your point of view ? if the data you exchange back and forth is large or is nested then might be the issue. – Gntem Apr 11 '17 at 21:41
  • JSON de/encoding is probably implemented there in native code in optimized fashion directly in the JS VM. Yeap, i pass few nested arrays – Michael Kors Apr 11 '17 at 21:45