Skip to content

Of JSON and Protocols

Robin Lambertz edited this page Apr 5, 2015 · 1 revision

Note : The following is an unorganized log of my random thoughts, mostly copy-pasted from gitter. I'll go through this and re-organize it eventually.

What is a Protocol ?

A Protocol, at its base, is just a bunch of dataTypes put together, with one of the dataTypes promoted as the "main" dataType. Take minecraft (which is what this library was built for originally) : There is one main dataType, the "packet" type, which is defined by a length prefix, a packet type, and finally a huge switch.

What is a DataType then ?

A dataType is, in effect, the serializer and deserializers that Protocols requires to serialize the protocol. It can be defined in two different ways :

  • In the JSON, by extending an existing dataType. The following example creates a datatype named "position" which reads 2 ints, named x and y :
{ "dataTypes": {
  "position": { "type": "struct", "typeArgs": { "fields": [
    { "name": "x", "type": "s32" },
    { "name": "y", "type": "s32" }
  ]}}}
}
  • With a helper function of your version of Protocols. The following example creates a datatype named "position" which reads one int, and splits it in two (one with the first 24 bits, the other with the remaining 8) :
function read(buffer) {
  var tmp = buffer.readInt32BE();
  return { x: tmp >> 8, y: tmp & 0xFF };
}

function write(value, buffer) {
  buffer.writeInt32BE(value.x << 8 | value.y);
}

module.exports = function(createDataType) {
  return {
    "position": createDataType(read, write, 4)
  }
};

DataType Dependency management

TODO