pygnetic Package¶
Network library for Pygame.
- pygnetic.init([events, event_val, logging_lvl, n_adapter, s_adapter])[source]¶
Initialize network library.
Parameters: - events – allow sending Pygame events (default False)
- event_val – set event.NETWORK as pygame.USEREVENT + event_val (default: None)
- logging_lvl – level of logging messages (default logging.INFO (see: Basic Logging Tutorial), None to skip initializing logging module)
- n_adapter (string or list of strings) – name(s) of network library, first available will be used (default: [‘enet’, ‘socket’])
- s_adapter (string or list of strings) – name(s) of serialization library, first available will be used (default: [‘msgpack’, ‘json’])
Returns: True if initialization ended with success
- pygnetic.register([name, field_names, **kwargs])[source]¶
Register new message type in message.message_factory.
Parameters: - name – name of message class
- field_names – list of names of message fields
- kwargs – additional keyword arguments for send method
Returns: message class (namedtuple)
- class pygnetic.Client(*args, **kwargs)¶
Proxy class for selected network adapter.
Parameters: n_adapter – override default network adapter for class instance (default: None - module selected with init())
- class pygnetic.Server(*args, **kwargs)¶
Proxy class for selected network adapter.
Parameters: n_adapter – override default network adapter for class instance (default: None - module selected with init())
- class pygnetic.Handler¶
handler.Handler binding.
client Module¶
Module containing base class for adapters representing network clients.
- class pygnetic.client.Client([conn_limit, message_factory, *args, **kwargs])[source]¶
Base class representing network client.
Parameters: - con_limit (int) – maximum amount of created connections (default: 1)
- message_factory – custom instance of MessageFactory (default: Client.message_factory)
- args – additional arguments for network adapter
- kwargs – additional keyword arguments for network adapter
Example:
client = pygnetic.client.Client() connection = client.connect("localhost", 10000) while True: client.update()
- message_factory¶
MessageFactory instance used for new connections. (default: message.message_factory)
- connect(host, port[, message_factory, **kwargs])[source]¶
Connects to specified address.
Parameters: - host (string) – IP address or name of host
- port (int) – port of host
- message_factory – MessageFactory used for new connection (default: message_factory)
- kwargs – additional keyword arguments for network adapter
Returns: new Connection
connection Module¶
Module containing base class for adapters representing network connections.
- class pygnetic.connection.Connection(parent, conn_obj, message_factory)[source]¶
Class allowing to send messages
Parameters: - parent – parent Client or Server
- conn_obj – connection object
- message_factory – MessageFactory object
Sending is possible in two ways:
- using net_message_name() methods, where message_name is name of message registered in MessageFactory
- using send() method with message as argument
Example:
# assuming chat_msg message is already defined connection.net_chat_msg('Tom', 'Test message') # alternative connection.send(chat_msg, 'Tom', 'Test message') # or connection.send('chat_msg', 'Tom', 'Test message')
- address¶
Connection address
- connected¶
True if connected
- data_sent¶
Amount of data sent
- data_received¶
Amount of data received
- messages_sent¶
Amount of messages sent
- messages_received¶
Amount of messages received
- add_handler(handler)[source]¶
Add new Handler to handle messages.
Parameters: handler – instance of Handler subclass
- disconnect([*args])[source]¶
Request a disconnection.
Parameters: args – additional arguments for network adapter
- net_message_name([*args, **kwargs])¶
Send message_name messagge to remote host.
Parameters: - args – parameters used to initialize message object
- kwargs – keyword parameters used to initialize message object
It uses __getattr__ mechanism to add net_message_name() partial method to class and call it. Any subsequent call is realized by new method.
- send(message[, *args, **kwargs])[source]¶
Send message to remote host.
Parameters: - message – class created by register() or message name
- args – parameters used to initialize message object
- kwargs – keyword parameters used to initialize message object
event Module¶
Module defining Pygame events.
- pygnetic.event.NETWORK¶
- pygnetic.event.NET_DISCONNECTED¶
- pygnetic.event.NET_CONNECTED¶
- pygnetic.event.NET_ACCEPTED¶
- pygnetic.event.NET_RECEIVED¶
Event attributes:
- Connected event
- Disconnected event
- Accepted event
- Received event
type = NETWORKnet_type = NET_RECEIVEDconnection – connectionmessage – received messagemsg_type – message type
Example:
for e in pygame.event.get():
if e.type == event.NETWORK:
if e.net_type == event.NET_CONNECTED:
print 'connected'
elif e.net_type == event.NET_DISCONNECTED:
print 'disconnected'
elif e.net_type == event.NET_RECEIVED:
# assuming chat_msg message is already defined
if e.msg_type == chat_msg:
print '%s: %s' % (e.message.player, e.message.msg)
else:
print 'received:', e.message
Note
To use events you need to enable them with init()
handler Module¶
Module containing Handler base class.
- class pygnetic.handler.Handler[source]¶
Base class for objects handling messages through net_message_name() methods
- connection¶
Proxy to instance of Connection derived class
- net_message_name(message[, **kwargs])¶
Called when message_name message is received
Parameters: - message – received message
- kwargs – additional keyword arguments from network adapter
- on_recive(message[, **kwargs])[source]¶
Called when message is received, but no corresponding net_message_name method exist.
Parameters: - message – received message
- kwargs – additional keyword arguments from network adapter
message Module¶
Module containing MessageFactory and predefined messages
- pygnetic.message.message_factory¶
Default instance of MessageFactory used by other modules.
- class pygnetic.message.MessageFactory([s_adapter])[source]¶
Class allowing to register new message types and pack/unpack them.
Parameters: s_adapter – serialization adapter (default: None - module selected with init()) Example:
chat_msg = MessageFactory.register('chat_msg', ('player', 'msg')) data = MessageFactory.pack(chat_msg('Tom', 'Test message')) message = MessageFactory.unpack(data) player = message.player msg = message.msg
Note
You can create more instances of MessageFactory when you want to separate messages for different connections in Client.
- get_by_name(name)[source]¶
Returns message class with given name.
Parameters: name – name of message Returns: message class (namedtuple)
- get_by_type(type_id)[source]¶
Returns message class with given type_id.
Parameters: type_id – type identifier of message Returns: message class (namedtuple)
- get_hash()[source]¶
Calculate and return hash.
Hash depends on registered messages and used serializing library.
Returns: int
- get_params(message_cls)[source]¶
Return dict containing sending keyword arguments
Parameters: message_cls – message class created by register Returns: dict
- get_type_id(message_cls)[source]¶
Return message class type_id
Parameters: message_cls – message class created by register Returns: int
- pack(message)[source]¶
Pack data to string.
Parameters: message – object of class created by register Returns: string
- register(name[, field_names, **kwargs])[source]¶
Register new message type.
Parameters: - name – name of message class
- field_names – list of names of message fields
- kwargs – additional keyword arguments for send method
Returns: message class (namedtuple)
- reset_context(context)[source]¶
Prepares object to behave as context for stream unpacking.
Parameters: context – object which will be prepared
- unpack(data)[source]¶
Unpack message from string.
Parameters: data – packed message data as a string Returns: message
- unpack_all(data, context)[source]¶
Feed unpacker with data from stream and unpack all messages.
Parameters: - data – packed message(s) data as a string
- context – object previously prepared with reset_context()
Returns: iterator over messages
server Module¶
Module containing base class for adapters representing network servers.
- class pygnetic.server.Server([host, port, conn_limit, handler, message_factory, *args, **kwargs])[source]¶
Class representing network server.
Parameters: - host (string) – IP address or name of host (default: “” - any)
- port (int) – port of host (default: 0 - any)
- con_limit (int) – maximum amount of created connections (default: 4)
- handler – custom Handler derived class (default: Server.handler)
- message_factory – custom instance of MessageFactory (default: Server.message_factory)
- args – additional arguments for network adapter
- kwargs – additional keyword arguments for network adapter
- address¶
Server address.
- handler¶
Class derived from Handler used to handle incoming messages. New instance is created for every new connection.
- message_factory¶
MessageFactory instance used for new connections. (default: message.message_factory)
- connections([exclude])[source]¶
Returns iterator over connections.
Parameters: exclude – list of connections to exclude Returns: iterator over connections
Small FAQ¶
- Why I have to register message? Can’t I just use dictionary to send it?
register() creates a compact data structure - 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 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 True >>> 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 of 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.
- How can I change MessageFactory used in Client or Server?
Class scope - every class instance will use it:
import pygnetic as net mf = net.message.MessageFactory() mf.register(...) class Client(net.Client): message_factory = mf net.init() client = Client()
Instance scope - only one instance will use it:
import pygnetic as net mf = net.message.MessageFactory() mf.register(...) net.init() client = net.Client(message_factory=mf)
- How can I change adapter used to create Client or Server?
Class scope - every class instance will use it:
import pygnetic as net class Client(net.Client): adapter = 'socket' net.init() client = Client()
Instance scope - only one instance will use it:
import pygnetic as net net.init() client = net.Client(adapter = 'enet')
Glossary¶
- network adapter
- class providing unified interface for different network libraries
- serialization adapter
- class providing unified interface for different serialization libraries