Commits

Szymon Wróblewski committed 401ad42

renamed Receiver to Handler, PacketManager to MessageFactory and names of all corresponding function and parameter

Comments (0)

Files changed (13)

pygame_network/__init__.py

-import packet
+import message
 import connection
 import syncobject
 from client import Client
 from server import Server
-from receiver import Receiver
+from handler import Handler
 try:
     import event
 except ImportError:
     pass
 
-register = packet.PacketManager.register
+register = message.MessageFactory.register

pygame_network/client.py

 import logging
 import enet
-from packet import PacketManager
+from message import MessageFactory
 from connection import Connection
 
 _logger = logging.getLogger(__name__)
         self._peers = {}
         self._peer_cnt = 0
 
-    def connect(self, address, port, channels=2, packet_manager=PacketManager):
+    def connect(self, address, port, channels=2, message_factory=MessageFactory):
         peer_id = self._peer_cnt = self._peer_cnt + 1
         peer_id = str(peer_id)
-        # Can't register packets after connection
-        packet_manager._frozen = True
+        # Can't register messages after connection
+        message_factory._frozen = True
         address = enet.Address(address, port)
-        peer = self.host.connect(address, channels, packet_manager.get_hash())
+        peer = self.host.connect(address, channels, message_factory.get_hash())
         peer.data = peer_id
-        connection = Connection(self, peer, packet_manager)
+        connection = Connection(self, peer, message_factory)
         self._peers[peer_id] = connection
         return connection
 

pygame_network/connection.py

 from weakref import proxy
 from functools import partial
 import enet
-from packet import PacketManager
+from message import MessageFactory
 
 _logger = logging.getLogger(__name__)
 
 # dummy events
 def _connected_event(connection): pass
 def _disconnected_event(connection): pass
-def _received_event(connection, channel, packet, packet_id): pass
-def _response_event(connection, channel, packet, packet_id): pass
+def _received_event(connection, channel, message, message_id): pass
+def _response_event(connection, channel, message, message_id): pass
 
 STATE_ACKNOWLEDGING_CONNECT = enet.PEER_STATE_ACKNOWLEDGING_CONNECT
 STATE_ACKNOWLEDGING_DISCONNECT = enet.PEER_STATE_ACKNOWLEDGING_DISCONNECT
 
 
 class Connection(object):
-    """Class allowing to send packets
+    """Class allowing to send messages
 
     It's created by by Client or Server, shouldn't be created manually.
 
     Sending is possible in two ways:
-    * using net_<packet_name> methods, where <packet_name>
-      is name of packet registered in PacketManager
-    * using send method with packet as argument
+    * using net_<message_name> methods, where <message_name>
+      is name of message registered in MessageFactory
+    * using send method with message as argument
 
     Attributes:
         parent - proxy to Client / Server instance
         peer - Enet peer instance
     """
 
-    def __init__(self, parent, peer, packet_manager=PacketManager):
+    def __init__(self, parent, peer, message_factory=MessageFactory):
         self.parent = proxy(parent)
         self.peer = peer
-        self._packet_cnt = 0
-        self._packet_manager = packet_manager
-        self._receivers = []
+        self._message_cnt = 0
+        self._message_factory = message_factory
+        self._handlers = []
 
     def __del__(self):
         self.peer.disconnect_now()
     def __getattr__(self, name):
         parts = name.split('_', 1)
         if len(parts) == 2 and parts[0] == 'net' and\
-                parts[1] in self._packet_manager._packet_names:
-            p = partial(self._send, self._packet_manager.get_by_name(parts[1]))
-            p.__doc__ = "Send %s packet to remote host\n\n"\
-                "Host.net_%s: return packet_id" % \
-                (parts[1], self._packet_manager._packet_names[parts[1]].__doc__)
+                parts[1] in self._message_factory._message_names:
+            p = partial(self._send, self._message_factory.get_by_name(parts[1]))
+            p.__doc__ = "Send %s message to remote host\n\n"\
+                "Host.net_%s: return message_id" % \
+                (parts[1], self._message_factory._message_names[parts[1]].__doc__)
             # add new method so __getattr__ is no longer needed
             setattr(self, name, p)
             return p
             raise AttributeError("'%s' object has no attribute '%s'" %
                                  (type(self).__name__, name))
 
-    def send(self, packet, *args, **kwargs):
-        """Send packet to remote host
+    def send(self, message, *args, **kwargs):
+        """Send message to remote host
 
-        Connection.send(packet, *args, **kwargs): return int
+        Connection.send(message, *args, **kwargs): return int
 
-        packet - class created by PacketManager.register or packet name
+        message - class created by MessageFactory.register or message name
 
-        args and kwargs are used to initialize packet object.
-        Returns packet id which can be used to retrieve response from
+        args and kwargs are used to initialize message object.
+        Returns message id which can be used to retrieve response from
         Pygame event queue if sending was successful.
         """
-        if isinstance(packet, basestring):
-            packet = self._packet_manager.get_by_name(packet)
-        self._send(packet, *args, **kwargs)
+        if isinstance(message, basestring):
+            message = self._message_factory.get_by_name(message)
+        self._send(message, *args, **kwargs)
 
-    def _send(self, packet, *args, **kwargs):
-        _, channel, flags = self._packet_manager.get_params(packet)
+    def _send(self, message, *args, **kwargs):
+        _, channel, flags = self._message_factory.get_params(message)
         flags = kwargs.get('flags', flags)
         channel = kwargs.get('channel', channel)
-        packet_id = self._packet_cnt = self._packet_cnt + 1
-        packet = packet(*args, **kwargs)
-        data = self._packet_manager.pack(packet_id, packet)
+        message_id = self._message_cnt = self._message_cnt + 1
+        message = message(*args, **kwargs)
+        data = self._message_factory.pack(message_id, message)
         if self.peer.send(channel, enet.Packet(data, flags)) == 0:
-            return packet_id
+            return message_id
 
     def _receive(self, data, channel):
-        packet_id, packet = self._packet_manager.unpack(data)
-        name = packet.__class__.__name__
-        _logger.info('Received %s packet', name)
+        message_id, message = self._message_factory.unpack(data)
+        name = message.__class__.__name__
+        _logger.info('Received %s message', name)
         name = 'net_' + name
-        _received_event(self, channel, packet, packet_id)
-        for r in self._receivers:
-            getattr(r, name, r.on_recive)(channel, packet_id, packet)
+        _received_event(self, channel, message, message_id)
+        for r in self._handlers:
+            getattr(r, name, r.on_recive)(channel, message_id, message)
 
     def _connect(self):
         _connected_event(self)
-        for r in self._receivers:
+        for r in self._handlers:
             r.on_connect()
 
     def _disconnect(self):
         _disconnected_event(self)
-        for r in self._receivers:
+        for r in self._handlers:
             r.on_disconnect()
 
     def disconnect(self):
 
     def disconnect_later(self):
         """Request a disconnection from a peer, but only after all queued
-        outgoing packets are sent.
+        outgoing messages are sent.
         """
         self.peer.disconnect_later()
 
         """
         self.peer.disconnect_now()
 
-    def add_receiver(self, receiver):
-        """Add new Receiver to handle packets.
+    def add_handler(self, handler):
+        """Add new Receiver to handle messages.
 
-        Connection.add_receiver(receiver)
+        Connection.add_handler(handler)
 
-        receiver - instance of Receiver subclass
+        handler - instance of Receiver subclass
         """
-        self._receivers.append(receiver)
-        receiver.connection = proxy(self)
+        self._handlers.append(handler)
+        handler.connection = proxy(self)
 
     @property
     def state(self):

pygame_network/event.py

     }))
 
 
-def _received_event(connection, channel, packet, packet_id):
+def _received_event(connection, channel, message, message_id):
     pygame.event.post(Event(NETWORK, {
         'net_type': NET_RECEIVED,
         #'connection': proxy(connection),
         'connection': connection,
         'channel': channel,
-        'packet': packet,
-        'p_id': packet_id,
-        'p_type': packet.__class__
+        'message': message,
+        'msg_id': message_id,
+        'msg_type': message.__class__
     }))
 
 
-def _response_event(connection, channel, packet, packet_id):
+def _response_event(connection, channel, message, message_id):
     pygame.event.post(Event(NETWORK, {
         'net_type': NET_RESPONSE,
         #'connection': proxy(connection),
         'connection': connection,
         'channel': channel,
-        'packet': packet,
-        'p_id': packet_id,
-        'p_type': packet.__class__
+        'message': message,
+        'msg_id': message_id,
+        'msg_type': message.__class__
     }))

pygame_network/handler.py

+class Handler(object):
+    """Base class for objects handling packets through
+    net_packet_name(channel, message_id, message) functions
+    """
+    def on_connect(self):
+        pass
+
+    def on_disconnect(self):
+        pass
+
+    def on_recive(self, channel, message_id, message):
+        pass

pygame_network/message.py

+import logging
+from collections import namedtuple
+from weakref import WeakKeyDictionary, WeakValueDictionary
+import enet
+try:
+    import msgpack as s_lib
+    _packer = s_lib.Packer()
+    _unpacker = s_lib.Unpacker()
+    _pack = _packer.pack
+    _unpack = lambda data: _unpacker.feed(data) or _unpacker.unpack()
+except ImportError:
+    import json as s_lib
+    _packer = s_lib.JSONEncoder()
+    _unpacker = s_lib.JSONDecoder()
+    _pack = _packer.encode
+    _unpack = _unpacker.decode
+
+_logger = logging.getLogger(__name__)
+
+__all__ = ('MessageFactory', 'MessageError')
+
+
+class MessageError(Exception):
+    pass
+
+
+class MessageFactory(object):
+    """Class allowing to register new message types and pack/unpack them.
+
+    example:
+        chat_msg = MessageFactory.register('chat_msg', ('player', 'msg'),
+                                          enet.PACKET_FLAG_RELIABLE)
+        MessageFactory.pack(chat_msg('Tom', 'Test message'))
+    """
+    _message_names = {}  # mapping name -> message
+    _message_types = WeakValueDictionary()  # mapping type_id -> message
+    _message_params = WeakKeyDictionary()  # mapping message -> type_id, send par
+    _type_id_cnt = 0
+    _frozen = False
+    _hash = None
+
+    def __init__(self):
+        # override class variables with instance variables
+        cls = self.__class__
+        self._message_names = cls._message_names.copy()
+        self._message_types = cls._message_types.copy()
+        self._message_params = cls._message_params.copy()
+        self._type_id_cnt = cls._type_id_cnt
+        self._frozen = False
+        self._hash = None
+
+    @classmethod
+    def register(cls, name, field_names=tuple(), channel=0, flags=enet.PACKET_FLAG_RELIABLE):
+        """Register new message type
+
+        MessageFactory.register(name, field_names, channel, flags): return class
+
+        name - name of message class
+        field_names - names of message fields
+
+        Warning: All packets must be registered in THE SAME ORDER in client and
+        server, BEFORE creating any connection.
+
+        Returns namedtuple class.
+        """
+        if cls._frozen == True:
+            raise MessageError("Can't register new messages after "\
+                              "connection establishment")
+        type_id = cls._type_id_cnt = cls._type_id_cnt + 1
+        packet = namedtuple(name, field_names)
+        cls._message_names[name] = packet
+        cls._message_types[type_id] = packet
+        cls._message_params[packet] = (type_id, channel, flags)
+        return packet
+
+    @classmethod
+    def pack(cls, message_id, message):
+        """Pack data to string
+
+        MessageFactory.pack(packet_id, packet_obj): return string
+
+        message_id - identifier of message
+        message - object of class created by register
+
+        Returns message packed in string, ready to send.
+        """
+        type_id = cls._message_params[message.__class__][0]
+        message = (type_id, message_id) + message
+        cls._message_cnt = message_id
+        return _pack(message)
+
+    @classmethod
+    def unpack(cls, data):
+        """Unpack data from string, return message_id and message
+
+        MessageFactory.unpack(data): return (message_id, message)
+
+        data - packed message data as a string
+        """
+        message = _unpack(data)
+        try:
+            type_id, packet_id = message[:2]
+            return packet_id, cls._message_types[type_id](*message[2:])
+        except KeyError:
+            _logger.warning('Unknown message type_id: %s', type_id)
+        except:
+            _logger.warning('Message unpacking error: %s', message)
+        return None, None
+
+    @classmethod
+    def get_by_name(cls, name):
+        """Returns message class with given name
+
+        MessageFactory.get_by_name(name): return class
+
+        name - name of message
+
+        Returns namedtuple class.
+        """
+        return cls._message_names[name]
+
+    @classmethod
+    def get_by_type(cls, type_id):
+        """Returns message class with given type_id
+
+        MessageFactory.get_by_type(name): return class
+
+        type_id - type identifier of message
+
+        Returns namedtuple class.
+        """
+        return cls._message_types[type_id]
+
+    @classmethod
+    def get_params(cls, message):
+        """Return tuple containing type_id, channel and sending flags
+
+        MessageFactory.get_params(message): return (int, int, int)
+
+        message - message class created by register
+        """
+        return cls._message_params[message]
+
+    @classmethod
+    def get_hash(cls):
+        if cls._frozen:
+            if cls._hash is None:
+                ids = cls._message_types.keys()
+                ids.sort()
+                l = list()
+                l.append(s_lib.__name__)
+                for i in ids:
+                    p = cls._message_types[i]
+                    l.append((i, p.__name__, p._fields))
+                # should be the same on 32 & 64 platforms
+                cls._hash = hash(tuple(l)) & 0xffffffff
+            return cls._hash
+        else:
+            _logger.warning('Attempt to get hash of not frozen MessageFactory')
+
+
+update_remoteobject = MessageFactory.register('update_remoteobject', (
+    'type_id',
+    'obj_id',
+    'variables'
+), 1, 0)
+chat_msg = MessageFactory.register('chat_msg', (
+    'player',
+    'msg'
+))

pygame_network/packet.py

-import logging
-from collections import namedtuple
-from weakref import WeakKeyDictionary, WeakValueDictionary
-import enet
-try:
-    import msgpack as s_lib
-    _packer = s_lib.Packer()
-    _unpacker = s_lib.Unpacker()
-    _pack = _packer.pack
-    _unpack = lambda data: _unpacker.feed(data) or _unpacker.unpack()
-except ImportError:
-    import json as s_lib
-    _packer = s_lib.JSONEncoder()
-    _unpacker = s_lib.JSONDecoder()
-    _pack = _packer.encode
-    _unpack = _unpacker.decode
-
-_logger = logging.getLogger(__name__)
-
-__all__ = ('PacketManager', 'PacketError')
-
-
-class PacketError(Exception):
-    pass
-
-
-class PacketManager(object):
-    """Class allowing to register new packet types and pack/unpack them.
-
-    example:
-        chat_msg = PacketManager.register('chat_msg', ('player', 'msg'),
-                                          enet.PACKET_FLAG_RELIABLE)
-        PacketManager.pack(chat_msg('Tom', 'Test message'))
-    """
-    _packet_names = {}  # mapping name -> packet
-    _packet_types = WeakValueDictionary()  # mapping type_id -> packet
-    _packet_params = WeakKeyDictionary()  # mapping packet -> type_id, send par
-    _type_id_cnt = 0
-    _frozen = False
-    _hash = None
-
-    def __init__(self):
-        # override class variables with instance variables
-        cls = self.__class__
-        self._packet_names = cls._packet_names.copy()
-        self._packet_types = cls._packet_types.copy()
-        self._packet_params = cls._packet_params.copy()
-        self._type_id_cnt = cls._type_id_cnt
-        self._frozen = False
-        self._hash = None
-
-    @classmethod
-    def register(cls, name, field_names=tuple(), channel=0, flags=enet.PACKET_FLAG_RELIABLE):
-        """Register new packet type
-
-        PacketManager.register(name, field_names, channel, flags): return class
-
-        name - name of packet class
-        field_names - names of packet fields
-
-        Warning: All packets must be registered in THE SAME ORDER in client and
-        server, BEFORE creating any connection.
-
-        Returns namedtuple class.
-        """
-        if cls._frozen == True:
-            raise PacketError("Can't register new packets after "\
-                              "connection establishment")
-        type_id = cls._type_id_cnt = cls._type_id_cnt + 1
-        packet = namedtuple(name, field_names)
-        cls._packet_names[name] = packet
-        cls._packet_types[type_id] = packet
-        cls._packet_params[packet] = (type_id, channel, flags)
-        return packet
-
-    @classmethod
-    def pack(cls, packet_id, packet):
-        """Pack data to string
-
-        PacketManager.pack(packet_id, packet_obj): return string
-
-        packet_id - identifier of packet
-        packet - object of class created by register
-
-        Returns packet packed in string, ready to send.
-        """
-        type_id = cls._packet_params[packet.__class__][0]
-        packet = (type_id, packet_id) + packet
-        cls._packet_cnt = packet_id
-        return _pack(packet)
-
-    @classmethod
-    def unpack(cls, data):
-        """Unpack data from string, return packet_id and packet
-
-        PacketManager.unpack(data): return (packet_id, packet)
-
-        data - packet data as a string
-        """
-        packet = _unpack(data)
-        try:
-            type_id, packet_id = packet[:2]
-            return packet_id, cls._packet_types[type_id](*packet[2:])
-        except KeyError:
-            _logger.warning('Unknown packet type_id: %s', type_id)
-        except:
-            _logger.warning('Packet unpacking error: %s', packet)
-        return None, None
-
-    @classmethod
-    def get_by_name(cls, name):
-        """Returns packet class with given name
-
-        PacketManager.get_by_name(name): return class
-
-        name - name of packet
-        """
-        return cls._packet_names[name]
-
-    @classmethod
-    def get_by_type(cls, type_id):
-        """Returns packet class with given type_id
-
-        PacketManager.get_by_type(name): return class
-
-        type_id - type identifier of packet
-        """
-        return cls._packet_types[type_id]
-
-    @classmethod
-    def get_params(cls, packet):
-        """Return tuple containing type_id, channel and sending flags
-
-        PacketManager.get_params(packet): return (int, int, int)
-
-        packet - packet class created by register
-        """
-        return cls._packet_params[packet]
-
-    @classmethod
-    def get_hash(cls):
-        if cls._frozen:
-            if cls._hash is None:
-                ids = cls._packet_types.keys()
-                ids.sort()
-                l = list()
-                l.append(s_lib.__name__)
-                for i in ids:
-                    p = cls._packet_types[i]
-                    l.append((i, p.__name__, p._fields))
-                # should be the same on 32 & 64 platforms
-                cls._hash = hash(tuple(l)) & 0xffffffff
-            return cls._hash
-        else:
-            _logger.warning('Attempt to get hash of not frozen PacketManager')
-
-
-update_remoteobject = PacketManager.register('update_remoteobject', (
-    'type_id',
-    'obj_id',
-    'variables'
-), 1, 0)
-chat_msg = PacketManager.register('chat_msg', (
-    'player',
-    'msg'
-))

pygame_network/receiver.py

-class Receiver(object):
-    """Base class for objects receiving packets through net_packet_name
-    functions
-    """
-    def on_connect(self):
-        pass
-
-    def on_disconnect(self):
-        pass
-
-    def on_recive(self, channel, packet_id, packet):
-        pass

pygame_network/server.py

 from weakref import proxy
 from functools import partial
 import enet
-from receiver import Receiver
-from packet import PacketManager
+from handler import Handler
+from message import MessageFactory
 from connection import Connection
 
 _logger = logging.getLogger(__name__)
 
 
 class Server(object):
-    packet_manager = PacketManager
-    receiver_cls = None
+    message_factory = MessageFactory
+    handler_cls = None
 
     def __init__(self, address='', port=0, connections_limit=4, # max 4095
                  channel_limit=0, in_bandwidth=0, out_bandwidth=0):
                               in_bandwidth, out_bandwidth)
         self.peers = {}
         self._peer_cnt = 0
-        self.packet_manager._frozen = True
+        self.message_factory._frozen = True
 
     def step(self, timeout=0):
         host = self.host
         event = host.service(timeout)
         while event is not None:
             if event.type == enet.EVENT_TYPE_CONNECT:
-                if event.data == self.packet_manager.get_hash():
+                if event.data == self.message_factory.get_hash():
                     _logger.info('Connection with %s accepted', event.peer.address)
                     peer_id = self._peer_cnt = self._peer_cnt + 1
                     peer_id = str(peer_id)
                     event.peer.data = peer_id
-                    connection = Connection(self, event.peer, self.packet_manager)
-                    if issubclass(self.receiver_cls, Receiver):
-                        receiver = self.receiver_cls()
-                        receiver.server = proxy(self)
-                        connection.add_receiver(receiver)
+                    connection = Connection(self, event.peer, self.message_factory)
+                    if issubclass(self.handler_cls, Handler):
+                        handler = self.handler_cls()
+                        handler.server = proxy(self)
+                        connection.add_handler(handler)
                     self.peers[peer_id] = connection
                     connection._connect()
                 else:
-                    _logger.warning('Connection with %s refused, PacketManager'\
+                    _logger.warning('Connection with %s refused, MessageFactory'\
                                     ' hash incorrect', event.peer.address)
                     event.peer.disconnect_now()
             elif event.type == enet.EVENT_TYPE_DISCONNECT:
                 self.peers[event.peer.data]._receive(event.packet.data, event.channelID)
             event = host.check_events()
 
-    def connections(self, exclude=[]):
+    def connections(self, exclude=None):
         if exclude is None:
             return self.peers.itervalues()
         else:
             return (c for c in self.peers.itervalues() if c not in exclude)
 
-    def receivers(self, exclude=[]):
-        return (c._receivers[0] for c in self.peers.itervalues() if c not in exclude)
+    def handlers(self, exclude=[]):
+        return (c._handlers[0] for c in self.peers.itervalues() if c not in exclude)

pygame_network/syncobject.py

 from weakref import WeakKeyDictionary
-from packet import *
+from message import *
 
 SYNCOBJECT_MODE_AUTO = 0
 SYNCOBJECT_MODE_MANUAL = 1
     to specify a tuple of variable names for synchronization.
     Each assignment to a variable defined in sync_var will notify
     SyncObjectManager which, depending on sync_mode, will either
-    prepare update packet (SYNCOBJECT_MODE_AUTO) or
+    prepare update message (SYNCOBJECT_MODE_AUTO) or
     wait with preparation for send_changes call (SYNCOBJECT_MODE_MANUAL).
     sync_flags overrides default enet sending flags.
     """
         """
         pass
 
-    def on_reply(self, packet_id):
+    def on_reply(self, message_id):
         """Callback when there was reply to change from remote host
         """
         pass
 
     def send_changes(self):
-        """Prepare update packet to send
+        """Prepare update message to send
 
         When sync_mode is SYNCOBJECT_MODE_MANUAL,
-        notify SyncObjectManager to prepare update packet
+        notify SyncObjectManager to prepare update message
         """
         pass
 
 
     @classmethod
     def changed(cls, obj, var_name):
-        """Prepares update packet
+        """Prepares update message
         """
         print '%s@%s updated' % (var_name, obj)
         # TODO: finish this
-        # TODO: push update packet to queue if in auto mode
+        # TODO: push update message to queue if in auto mode
 
-# TODO: pushing update packets from SyncObject
+# TODO: pushing update messages from SyncObject
 # TODO: mapping obj type and variables to ints
 
 
 import random
 import logging
 import pygame_network
-from pygame_network import Receiver, Client
+from pygame_network import Handler, Client
 
 
-class EchoReceiver(Receiver):
+class EchoHandler(Handler):
     def __init__(self):
         self.connected = None
         self.counter = 10
 
-    def net_echo(self, channel, packet_id, packet):
-        print 'packet #%d @ch%d: %s' % (packet_id, channel, packet)
+    def net_echo(self, channel, message_id, message):
+        print 'message #%d @ch%d: %s' % (message_id, channel, message)
 
     def on_connect(self):
         self.connected = True
     print 'connecting'
     client = Client()
     connection = client.connect("localhost", 54301)
-    receiver = EchoReceiver()
-    connection.add_receiver(receiver)
+    handler = EchoHandler()
+    connection.add_handler(handler)
     print 'client started'
-    while receiver.connected != False:
+    while handler.connected != False:
         client.step()
-        receiver.step()
+        handler.step()
 
 
 if __name__ == '__main__':
 from pygame_network.event import *
 
 
-def packet_status(screen, position, packets):
+def message_status(screen, position, packets):
     i = 0
     keys = packets.keys()
     keys.sort()
     pygame.display.flip()
 
     # Network init
-    pygame_network.event.init()
-    echo = pygame_network.packet.PacketManager.register('echo', ('msg',))
-    client = pygame_network.client.Client()
+    pygame_network.event.init()  # enable Pygame events
+    echo = pygame_network.register('echo', ('msg',))
+    client = pygame_network.Client()
     connection = None
 
     # Variables
     run = True
     limit = True
-    packets = {}
+    messages = {}
 
     while run:
         events = pygame.event.get()
                 if e.key == K_l:
                     limit = not limit
 
-            # Handling network packets
+            # Handling network messages
             if e.type == NETWORK and e.connection == connection:
                 if e.net_type == NET_CONNECTED:
                     connection_status(screen, (140, 38), True)
                 elif e.net_type == NET_DISCONNECTED:
                     connection_status(screen, (140, 38), None)
                     connection = None
-                    packets = {}
-                    packet_status(screen, (110, 62), packets)
+                    messages = {}
+                    message_status(screen, (110, 62), messages)
                 elif e.net_type == NET_RECEIVED:
-                    if e.p_type == echo:
-                        msg = e.packet.msg
-                        packets[e.p_id][1] = msg
-                        packet_status(screen, (110, 62), packets)
+                    if e.msg_type == echo:
+                        msg = e.message.msg
+                        messages[e.msg_id][1] = msg
+                        message_status(screen, (110, 62), messages)
             if e.type == QUIT or e.type == KEYDOWN and e.key == K_ESCAPE:
                 run = False
-        if len(packets) < 10 and connection is not None and connection.state == pygame_network.connection.STATE_CONNECTED:
+        if len(messages) < 10 and connection is not None and connection.state == pygame_network.connection.STATE_CONNECTED:
             msg = ''.join(random.sample('abcdefghijklmnopqrstuvwxyz', 10))
 
-            # Sending packets
-            p_id = connection.net_echo(msg)
+            # Sending messages
+            m_id = connection.net_echo(msg)
 
-            packets[p_id] = [msg, None]
-            packet_status(screen, (110, 62), packets)
+            messages[m_id] = [msg, None]
+            message_status(screen, (110, 62), messages)
         client.step()
         pygame.display.flip()
         if limit:
 import logging
 import pygame_network
-from pygame_network import Receiver, Server
+from pygame_network import Handler, Server
 
 
-class EchoReceiver(Receiver):
-    def net_echo(self, channel, packet_id, packet):
-        msg = packet.msg.upper()
+class EchoHandler(Handler):
+    def net_echo(self, channel, message_id, message):
+        msg = message.msg.upper()
         self.connection.net_echo(msg)
-        print 'packet #%d @ch%d: %s' % (packet_id, channel, packet)
+        print 'message #%d @ch%d: %s' % (message_id, channel, message)
 
 
 def main():
     pygame_network.register('echo', ('msg',))
     print 'starting server'
     server = Server(port=54301)
-    server.receiver_cls = EchoReceiver
+    server.handler_cls = EchoHandler
     print 'server started'
     run = True
     while run: