Jettison

Jettison is a library for encoding binary data into strings for transmission to JavaScript clients using things like WebSockets. This Python module is compatible with the JavaScript version at <https://github.com/noonat/jettison>.

Use Jettison to define a shared schema between the client and the server. Each schema can contain a number of definitions, and each definition can have a number of fields. You can then encode dictionaries, where each field in the definition maps to a key in the dictionary.

Here’s an example schema with two packets:

>>> import jettison
>>> schema = jettison.Schema()
>>> schema.define('spawn', [
...     {'key': 'entity_id', 'type': 'uint32'},
...     {'key': 'x', 'type': 'float64'},
...     {'key': 'y', 'type': 'float64'},
...     {'key': 'health', 'type': 'int16'},
... ])
<jettison.Definition object at 0x10fe6fd50>
>>> schema.define('health', [
...     {'key': 'entity_id', 'type': 'uint32'},
...     {'key': 'health', 'type': 'int16'}
... ])
<jettison.Definition object at 0x10fe82110>

You can then use the schema to dump a spawn dict:

>>> schema.dumps('spawn', {
...     'entity_id': 1,
...     'x': 0.5,
...     'y': -1.5,
...     'health': 100,
... })
'?à¿ø...'

Or load a string:

>>> schema.loads(_)
{'y': -1.5, 'x': 0.5, 'entity_id': 1, 'health': 100}

Note that you don’t need to specify the definition type on load, as the definition id is encoded into the packet. This is why the schemas must match on the client and server.

Types that are currently supported are:

Type Description
int8 1 byte signed integer. Range is -128 to 127 (inclusive).
int16 2 byte signed integer. Range is -32768 to 32767.
int32 4 byte signed integer. Range is -2147483648 to 2147483647.
uint8 1 byte unsigned integer. Range is 0 to 255.
uint16 2 byte unsigned integer. Range is 0 to 65535.
uint32 4 byte unsigned integer. Range is 0 to 4294967295.
float32 4 byte floating point number. Note that normal JavaScript numbers will be rounded to fit this size, so decoded values will only approximately equal the originals.
float64 8 byte floating point number. Normal JavaScript numbers are stored in this format, so these will be transmitted without rounding.
array A variable length array of another type. When you use this type, you must also specify a valueType field, which will specify the type of value in the array.
string A variable length string. JavaScript’s UTF-16 strings are encoded to UTF-8 for transmission.

Note that if you attempt to encode a value that is out of range of its type, an exception will be raised.

Indices and tables