pygnetic / doc / source / api / index.rst

Full commit

Small FAQ

Why I have to register message? Can't I just use dictionary to send it?

:meth:`~.message.MessageFactory.register` creates a compact data structure - :func:`namedtuple <collections.namedtuple>`, which contains only essential data, reducing overall amount of data to send. Take a look at example below and compare sizes of packed dictionary and structure created by :class:`~.message.MessageFactory`.

>>> import msgpack
>>> m1 = msgpack.packb({'action':'chat_msg', 'player':'Tom', 'msg':'Test message'})
>>> m1, len(m1)
('\x83\xa6action\xa8chat_msg\xa6player\xa3Tom\xa3msg\xacTest message', 45)
>>> import pygnetic as net
>>> net.init()
17:11:40 INFO     Using enet_adapter
17:11:40 INFO     Using msgpack_adapter
>>> chat_msg = net.register('chat_msg', ('player', 'msg'))
>>> m2 = net.message.message_factory.pack(chat_msg('Tom', 'Test message'))
>>> m2, len(m2)
('\x93\x02\xa3Tom\xacTest message', 19)

The only drawback of this method is the need to register the same messages in the same order in client and server.

Why order of registration messages is important?
As You may noticed in previous example, there is no string with type of message in packed data. That's because type is encoded as integer, depending on order of registration.