Commits

Szymon Wróblewski committed 5ae0116

preparing to use multiple network libraries, added nice init method

  • Participants
  • Parent commits 401ad42

Comments (0)

Files changed (18)

File pygame_network/__init__.py

+import logging
+from importlib import import_module
 import message
-import connection
 import syncobject
-from client import Client
-from server import Server
 from handler import Handler
-try:
-    import event
-except ImportError:
-    pass
 
 register = message.MessageFactory.register
+
+
+def init(events=False, event_val=1, logging_lvl=logging.INFO,
+         network=('enet',), serialization=('msgpack', 'json')):
+    global Client, Server, State
+    _logger = logging.getLogger(__name__)
+    if logging_lvl is not None:
+        logging.basicConfig(level=logging_lvl,
+                            format='%(asctime)s:%(levelname)s:%(message)s',
+                            datefmt='%H:%M:%S')
+    if isinstance(network, basestring):
+        network = (network,)
+    if isinstance(serialization, basestring):
+        serialization = (serialization,)
+    for name in network:
+        try:
+            _logger.debug("Trying to import network.%s_adapter", name)
+            nmod = import_module('pygame_network.network.%s_adapter' % name)
+            break
+        except ImportError as e:
+            _logger.debug("%s: %s", e.__class__.__name__, e.message)
+    else:
+        _logger.critical("Can't find any network module")
+        return
+    Client = nmod.Client
+    Server = nmod.Server
+    State = nmod.State
+    _logger.info("Using %s network module", name)
+    for name in serialization:
+        try:
+            _logger.debug("Trying to import serialization.%s_adapter", name)
+            smod = import_module('pygame_network.serialization.%s_adapter' % name)
+            break
+        except ImportError:
+            _logger.debug("%s: %s", e.__class__.__name__, e.message)
+    else:
+        _logger.critical("Can't find any serialization module")
+        return
+    message.s_lib = smod
+    _logger.info("Using %s serialization module", name)
+    print nmod
+    if events:
+        _logger.info("Enabling pygame events")
+        import event
+        event.init(event_val)

File pygame_network/client.py

-import logging
-import enet
-from message import MessageFactory
-from connection import Connection
-
-_logger = logging.getLogger(__name__)
-
-
-class Client(object):
-    """Class representing network client
-
-    Example:
-        client = pygame_network.client.Client()
-        connection = client.connect("localhost", 10000)
-        while True:
-            client.step()
-    """
-    def __init__(self, connections_limit=1, channel_limit=0, in_bandwidth=0, out_bandwidth=0):
-        self.host = enet.Host(None, connections_limit, channel_limit, in_bandwidth, out_bandwidth)
-        self._peers = {}
-        self._peer_cnt = 0
-
-    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 messages after connection
-        message_factory._frozen = True
-        address = enet.Address(address, port)
-        peer = self.host.connect(address, channels, message_factory.get_hash())
-        peer.data = peer_id
-        connection = Connection(self, peer, message_factory)
-        self._peers[peer_id] = connection
-        return connection
-
-    def step(self, timeout=0):
-        if len(self._peers) == 0:
-            return
-        host = self.host
-        event = host.service(timeout)
-        while event is not None:
-            if event.type == enet.EVENT_TYPE_CONNECT:
-                _logger.info('Connected to %s', event.peer.address)
-                self._peers[event.peer.data]._connect()
-            elif event.type == enet.EVENT_TYPE_DISCONNECT:
-                _logger.info('Disconnected from %s', event.peer.address)
-                self._peers[event.peer.data]._disconnect()
-                del self._peers[event.peer.data]
-            elif event.type == enet.EVENT_TYPE_RECEIVE:
-                _logger.info('Received data from %s', event.peer.address)
-                self._peers[event.peer.data]._receive(event.packet.data, event.channelID)
-            event = host.check_events()

File pygame_network/connection.py

-__all__ = ('Connection',
-           'STATE_ACKNOWLEDGING_CONNECT',
-           'STATE_ACKNOWLEDGING_DISCONNECT',
-           'STATE_CONNECTED',
-           'STATE_CONNECTING',
-           'STATE_CONNECTION_PENDING',
-           'STATE_CONNECTION_SUCCEEDED',
-           'STATE_DISCONNECTED',
-           'STATE_DISCONNECTING',
-           'STATE_DISCONNECT_LATER',
-           'STATE_ZOMBIE')
-
-import logging
-from weakref import proxy
-from functools import partial
-import enet
-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, 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
-STATE_CONNECTED = enet.PEER_STATE_CONNECTED
-STATE_CONNECTING = enet.PEER_STATE_CONNECTING
-STATE_CONNECTION_PENDING = enet.PEER_STATE_CONNECTION_PENDING
-STATE_CONNECTION_SUCCEEDED = enet.PEER_STATE_CONNECTION_SUCCEEDED
-STATE_DISCONNECTED = enet.PEER_STATE_DISCONNECTED
-STATE_DISCONNECTING = enet.PEER_STATE_DISCONNECTING
-STATE_DISCONNECT_LATER = enet.PEER_STATE_DISCONNECT_LATER
-STATE_ZOMBIE = enet.PEER_STATE_ZOMBIE
-
-
-class Connection(object):
-    """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_<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, message_factory=MessageFactory):
-        self.parent = proxy(parent)
-        self.peer = peer
-        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._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
-        else:
-            raise AttributeError("'%s' object has no attribute '%s'" %
-                                 (type(self).__name__, name))
-
-    def send(self, message, *args, **kwargs):
-        """Send message to remote host
-
-        Connection.send(message, *args, **kwargs): return int
-
-        message - class created by MessageFactory.register or message name
-
-        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(message, basestring):
-            message = self._message_factory.get_by_name(message)
-        self._send(message, *args, **kwargs)
-
-    def _send(self, message, *args, **kwargs):
-        _, channel, flags = self._message_factory.get_params(message)
-        flags = kwargs.get('flags', flags)
-        channel = kwargs.get('channel', channel)
-        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 message_id
-
-    def _receive(self, data, channel):
-        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, 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._handlers:
-            r.on_connect()
-
-    def _disconnect(self):
-        _disconnected_event(self)
-        for r in self._handlers:
-            r.on_disconnect()
-
-    def disconnect(self):
-        """Request a disconnection.
-        """
-        self.peer.disconnect()
-
-    def disconnect_later(self):
-        """Request a disconnection from a peer, but only after all queued
-        outgoing messages are sent.
-        """
-        self.peer.disconnect_later()
-
-    def disconnect_now(self):
-        """Force an immediate disconnection.
-        """
-        self.peer.disconnect_now()
-
-    def add_handler(self, handler):
-        """Add new Receiver to handle messages.
-
-        Connection.add_handler(handler)
-
-        handler - instance of Receiver subclass
-        """
-        self._handlers.append(handler)
-        handler.connection = proxy(self)
-
-    @property
-    def state(self):
-        """Connection state."""
-        return self.peer.state
-
-    @property
-    def address(self):
-        """Connection address."""
-        return self.peer.address

File pygame_network/event.py

 __all__ = ('NETWORK',
            'NET_CONNECTED',
            'NET_DISCONNECTED',
-           'NET_RECEIVED',
-           'NET_RESPONSE')
+           'NET_RECEIVED')
 
-from weakref import proxy
-import pygame
-from pygame.event import Event
-from pygame.locals import USEREVENT
-import connection
-
-NETWORK = USEREVENT + 1
+NETWORK = -1
 NET_CONNECTED = 0
 NET_DISCONNECTED = 1
 NET_RECEIVED = 2
-NET_RESPONSE = 3  # TODO: response !!
 
 
 def init(event_val=1):
-    global NETWORK
+    global NETWORK, connected, disconnected, received
+    import pygame
+    from pygame.event import Event
+    from pygame.locals import USEREVENT
     NETWORK = USEREVENT + event_val
-    connection._connected_event = _connected_event
-    connection._disconnected_event = _disconnected_event
-    connection._received_event = _received_event
-    connection._response_event = _response_event
 
+    def _connected(connection):
+        pygame.event.post(Event(NETWORK, {
+            'net_type': NET_CONNECTED,
+            #'connection': proxy(connection)
+            'connection': connection
+        }))
+    connected = _connected
 
-def _connected_event(connection):
-    pygame.event.post(Event(NETWORK, {
-        'net_type': NET_CONNECTED,
-        #'connection': proxy(connection)
-        'connection': connection
-    }))
+    def _disconnected(connection):
+        pygame.event.post(Event(NETWORK, {
+            'net_type': NET_DISCONNECTED,
+            #'connection': proxy(connection)
+            'connection': connection
+        }))
+    disconnected = _disconnected
 
+    def _received(connection, channel, message, message_id):
+        pygame.event.post(Event(NETWORK, {
+            'net_type': NET_RECEIVED,
+            #'connection': proxy(connection),
+            'connection': connection,
+            'channel': channel,
+            'message': message,
+            'msg_id': message_id,
+            'msg_type': message.__class__
+        }))
+    received = _received
 
-def _disconnected_event(connection):
-    pygame.event.post(Event(NETWORK, {
-        'net_type': NET_DISCONNECTED,
-        #'connection': proxy(connection)
-        'connection': connection
-    }))
 
+def connected(connection):
+    pass
 
-def _received_event(connection, channel, message, message_id):
-    pygame.event.post(Event(NETWORK, {
-        'net_type': NET_RECEIVED,
-        #'connection': proxy(connection),
-        'connection': connection,
-        'channel': channel,
-        'message': message,
-        'msg_id': message_id,
-        'msg_type': message.__class__
-    }))
 
+def disconnected(connection):
+    pass
 
-def _response_event(connection, channel, message, message_id):
-    pygame.event.post(Event(NETWORK, {
-        'net_type': NET_RESPONSE,
-        #'connection': proxy(connection),
-        'connection': connection,
-        'channel': channel,
-        'message': message,
-        'msg_id': message_id,
-        'msg_type': message.__class__
-    }))
+
+def received(connection, channel, message, message_id):
+    pass

File pygame_network/message.py

 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')
+_logger = logging.getLogger(__name__)
+s_lib = None
 
 
 class MessageError(Exception):
         type_id = cls._message_params[message.__class__][0]
         message = (type_id, message_id) + message
         cls._message_cnt = message_id
-        return _pack(message)
+        data = s_lib.pack(message)
+        _logger.debug("Packing message (length: %d)", len(data))
+        return data
 
     @classmethod
     def unpack(cls, data):
 
         data - packed message data as a string
         """
-        message = _unpack(data)
+        _logger.debug("Unpacking message (length: %d)", len(data))
+        message = s_lib.unpack(data)
         try:
             type_id, packet_id = message[:2]
             return packet_id, cls._message_types[type_id](*message[2:])

File pygame_network/network/__init__.py

Empty file added.

File pygame_network/network/enet_adapter/__init__.py

+from client import Client
+from server import Server
+from connection import State

File pygame_network/network/enet_adapter/client.py

+import logging
+import enet
+from ...message import MessageFactory
+from connection import Connection
+
+_logger = logging.getLogger(__name__)
+
+
+class Client(object):
+    """Class representing network client
+
+    Example:
+        client = pygame_network.client.Client()
+        connection = client.connect("localhost", 10000)
+        while True:
+            client.step()
+    """
+    def __init__(self, connections_limit=1, channel_limit=0, in_bandwidth=0, out_bandwidth=0):
+        self.host = enet.Host(None, connections_limit, channel_limit, in_bandwidth, out_bandwidth)
+        self._peers = {}
+        self._peer_cnt = 0
+        _logger.debug('Client created, connections limit: %d', connections_limit)
+
+    def connect(self, address, port, channels=2, message_factory=MessageFactory):
+        address = enet.Address(address, port)
+        _logger.info('Connecting to %s', address)
+        peer_id = self._peer_cnt = self._peer_cnt + 1
+        peer_id = str(peer_id)
+        # Can't register messages after connection
+        message_factory._frozen = True
+        _logger.debug('MessageFactory frozen')
+        peer = self.host.connect(address, channels, message_factory.get_hash())
+        peer.data = peer_id
+        connection = Connection(self, peer, message_factory)
+        self._peers[peer_id] = connection
+        return connection
+
+    def step(self, timeout=0):
+        if len(self._peers) == 0:
+            return
+        host = self.host
+        event = host.service(timeout)
+        while event is not None:
+            if event.type == enet.EVENT_TYPE_CONNECT:
+                _logger.info('Connected to %s', event.peer.address)
+                self._peers[event.peer.data]._connect()
+            elif event.type == enet.EVENT_TYPE_DISCONNECT:
+                _logger.info('Disconnected from %s', event.peer.address)
+                self._peers[event.peer.data]._disconnect()
+                del self._peers[event.peer.data]
+            elif event.type == enet.EVENT_TYPE_RECEIVE:
+                _logger.info('Received data from %s', event.peer.address)
+                self._peers[event.peer.data]._receive(event.packet.data, event.channelID)
+            event = host.check_events()

File pygame_network/network/enet_adapter/connection.py

+import logging
+from weakref import proxy
+from functools import partial
+import enet
+from ...message import MessageFactory
+from ... import event
+
+__all__ = ('Connection', 'State')
+_logger = logging.getLogger(__name__)
+
+
+class State(object):
+    ACKNOWLEDGING_CONNECT = enet.PEER_STATE_ACKNOWLEDGING_CONNECT
+    ACKNOWLEDGING_DISCONNECT = enet.PEER_STATE_ACKNOWLEDGING_DISCONNECT
+    CONNECTED = enet.PEER_STATE_CONNECTED
+    CONNECTING = enet.PEER_STATE_CONNECTING
+    CONNECTION_PENDING = enet.PEER_STATE_CONNECTION_PENDING
+    CONNECTION_SUCCEEDED = enet.PEER_STATE_CONNECTION_SUCCEEDED
+    DISCONNECTED = enet.PEER_STATE_DISCONNECTED
+    DISCONNECTING = enet.PEER_STATE_DISCONNECTING
+    DISCONNECT_LATER = enet.PEER_STATE_DISCONNECT_LATER
+    ZOMBIE = enet.PEER_STATE_ZOMBIE
+
+
+class Connection(object):
+    """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_<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, message_factory=MessageFactory):
+        self.parent = proxy(parent)
+        self.peer = peer
+        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._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
+        else:
+            raise AttributeError("'%s' object has no attribute '%s'" %
+                                 (type(self).__name__, name))
+
+    def send(self, message, *args, **kwargs):
+        """Send message to remote host
+
+        Connection.send(message, *args, **kwargs): return int
+
+        message - class created by MessageFactory.register or message name
+
+        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(message, basestring):
+            message = self._message_factory.get_by_name(message)
+        self._send(message, *args, **kwargs)
+
+    def _send(self, message, *args, **kwargs):
+        _, channel, flags = self._message_factory.get_params(message)
+        flags = kwargs.get('flags', flags)
+        channel = kwargs.get('channel', channel)
+        message_id = self._message_cnt = self._message_cnt + 1
+        name = message.__name__
+        message = message(*args, **kwargs)
+        data = self._message_factory.pack(message_id, message)
+        if self.peer.send(channel, enet.Packet(data, flags)) == 0:
+            _logger.info('Sent %s message on channel %d', name, channel)
+            return message_id
+
+    def _receive(self, data, channel):
+        message_id, message = self._message_factory.unpack(data)
+        name = message.__class__.__name__
+        _logger.info('Received %s message on channel %d', name, channel)
+        name = 'net_' + name
+        event.received(self, channel, message, message_id)
+        for r in self._handlers:
+            getattr(r, name, r.on_recive)(channel, message_id, message)
+
+    def _connect(self):
+        event.connected(self)
+        for r in self._handlers:
+            r.on_connect()
+
+    def _disconnect(self):
+        event.disconnected(self)
+        for r in self._handlers:
+            r.on_disconnect()
+
+    def disconnect(self):
+        """Request a disconnection.
+        """
+        self.peer.disconnect()
+
+    def disconnect_later(self):
+        """Request a disconnection from a peer, but only after all queued
+        outgoing messages are sent.
+        """
+        self.peer.disconnect_later()
+
+    def disconnect_now(self):
+        """Force an immediate disconnection.
+        """
+        self.peer.disconnect_now()
+
+    def add_handler(self, handler):
+        """Add new Receiver to handle messages.
+
+        Connection.add_handler(handler)
+
+        handler - instance of Receiver subclass
+        """
+        self._handlers.append(handler)
+        handler.connection = proxy(self)
+
+    @property
+    def state(self):
+        """Connection state."""
+        return self.peer.state
+
+    @property
+    def address(self):
+        """Connection address."""
+        return self.peer.address

File pygame_network/network/enet_adapter/server.py

+import logging
+from weakref import proxy
+import enet
+from ...handler import Handler
+from ...message import MessageFactory
+from connection import Connection
+
+_logger = logging.getLogger(__name__)
+
+
+class Server(object):
+    message_factory = MessageFactory
+    handler_cls = None
+
+    def __init__(self, address='', port=0, connections_limit=4, *args, **kwargs):
+        address = enet.Address(address, port)
+        self.host = enet.Host(address, connections_limit, *args, **kwargs)
+        self.peers = {}
+        self._peer_cnt = 0
+        _logger.debug('Server created %s, connections limit: %d', address, connections_limit)
+        self.message_factory._frozen = True
+        _logger.debug('MessageFactory frozen')
+
+
+    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.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.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, MessageFactory'\
+                                    ' hash incorrect', event.peer.address)
+                    event.peer.disconnect_now()
+            elif event.type == enet.EVENT_TYPE_DISCONNECT:
+                _logger.info('Disconnected from %s', event.peer.address)
+                self.peers[event.peer.data]._disconnect()
+                del self.peers[event.peer.data]
+            elif event.type == enet.EVENT_TYPE_RECEIVE:
+                _logger.info('Received data from %s', event.peer.address)
+                self.peers[event.peer.data]._receive(event.packet.data, event.channelID)
+            event = host.check_events()
+
+    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 handlers(self, exclude=[]):
+        return (c._handlers[0] for c in self.peers.itervalues() if c not in exclude)

File pygame_network/serialization/__init__.py

Empty file added.

File pygame_network/serialization/json_adapter.py

+import json
+_packer = json.JSONEncoder()
+_unpacker = json.JSONDecoder()
+pack = _packer.encode
+unpack = _unpacker.decode

File pygame_network/serialization/msgpack_adapter.py

+import msgpack
+_packer = msgpack.Packer()
+_unpacker = msgpack.Unpacker()
+pack = _packer.pack
+unpack = lambda data: _unpacker.feed(data) or _unpacker.unpack()

File pygame_network/server.py

-import logging
-from weakref import proxy
-from functools import partial
-import enet
-from handler import Handler
-from message import MessageFactory
-from connection import Connection
-
-_logger = logging.getLogger(__name__)
-
-
-class Server(object):
-    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):
-        address = enet.Address(address, port)
-        self.host = enet.Host(address, connections_limit, channel_limit,
-                              in_bandwidth, out_bandwidth)
-        self.peers = {}
-        self._peer_cnt = 0
-        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.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.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, MessageFactory'\
-                                    ' hash incorrect', event.peer.address)
-                    event.peer.disconnect_now()
-            elif event.type == enet.EVENT_TYPE_DISCONNECT:
-                _logger.info('Disconnected from %s', event.peer.address)
-                self.peers[event.peer.data]._disconnect()
-                del self.peers[event.peer.data]
-            elif event.type == enet.EVENT_TYPE_RECEIVE:
-                _logger.info('Received data from %s', event.peer.address)
-                self.peers[event.peer.data]._receive(event.packet.data, event.channelID)
-            event = host.check_events()
-
-    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 handlers(self, exclude=[]):
-        return (c._handlers[0] for c in self.peers.itervalues() if c not in exclude)

File test_client_1.py

 import random
 import logging
-import pygame_network
-from pygame_network.connection import STATE_CONNECTED, STATE_DISCONNECTED
+import pygame_network as net
 
 
 def main():
-    logging.basicConfig(level=logging.DEBUG)
-
-    pygame_network.register('echo', ('msg',))
-    print 'connecting'
-    client = pygame_network.Client()
+    net.init(logging_lvl=logging.DEBUG)
+    net.register('echo', ('msg',))
+    client = net.Client()
     connection = client.connect("localhost", 54301)
     counter = 0
-    print 'client started'
-    while connection.state != STATE_DISCONNECTED:
+    while connection.state != net.State.DISCONNECTED:
         client.step()
-        if counter < 10 and connection.state == STATE_CONNECTED:
+        if counter < 10 and connection.state == net.State.CONNECTED:
             msg = ''.join(random.sample('abcdefghijklmnopqrstuvwxyz', 10))
-            print("%s: out: %r" % (connection.address, msg))
+            logging.info('Sending: %s', msg)
             connection.net_echo(msg)
             counter += 1
 

File test_client_2.py

 import random
 import logging
-import pygame_network
-from pygame_network import Handler, Client
+import pygame_network as net
 
 
-class EchoHandler(Handler):
+class EchoHandler(net.Handler):
     def __init__(self):
         self.connected = None
         self.counter = 10
 
     def net_echo(self, channel, message_id, message):
-        print 'message #%d @ch%d: %s' % (message_id, channel, message)
+        logging.info('Received message #%d @ch%d: %s', message_id, channel, message)
 
     def on_connect(self):
         self.connected = True
     def step(self):
         if self.counter > 0 and self.connected == True:
             msg = ''.join(random.sample('abcdefghijklmnopqrstuvwxyz', 10))
-            print("%s: out: %r" % (self.connection.address, msg))
+            logging.info('Sending: %s', msg)
             self.connection.net_echo(msg)
             self.counter -= 1
 
 
 def main():
-    logging.basicConfig(level=logging.DEBUG)
-
-    pygame_network.register('echo', ('msg',))
-    print 'connecting'
-    client = Client()
+    net.init(logging_lvl=logging.DEBUG)
+    net.register('echo', ('msg',))
+    client = net.Client()
     connection = client.connect("localhost", 54301)
     handler = EchoHandler()
     connection.add_handler(handler)
-    print 'client started'
     while handler.connected != False:
         client.step()
         handler.step()

File test_client_3.py

 import logging
 import pygame
 from pygame.locals import *
-import pygame_network
-from pygame_network.event import *
+import pygame_network as net
 
 
 def message_status(screen, position, packets):
 
 
 def main():
-    logging.basicConfig(level=logging.DEBUG)
-
     # Pygame init
     pygame.init()
     screen = pygame.display.set_mode((800, 600))
     pygame.display.flip()
 
     # Network init
-    pygame_network.event.init()  # enable Pygame events
-    echo = pygame_network.register('echo', ('msg',))
-    client = pygame_network.Client()
+    net.init(events=True, logging_lvl=logging.DEBUG)  # enable Pygame events
+    echo = net.register('echo', ('msg',))
+    client = net.Client()
     connection = None
 
     # Variables
             if e.type == KEYDOWN:
                 if e.key == K_SPACE:
                     if connection is not None:
-                        if connection.state == pygame_network.connection.STATE_CONNECTED:
+                        if connection.state == net.State.CONNECTED:
                             connection.disconnect_later()
                             connection_status(screen, (140, 38), False)
                     else:
                     limit = not limit
 
             # Handling network messages
-            if e.type == NETWORK and e.connection == connection:
-                if e.net_type == NET_CONNECTED:
+            if e.type == net.event.NETWORK and e.connection == connection:
+                if e.net_type == net.event.NET_CONNECTED:
                     connection_status(screen, (140, 38), True)
-                elif e.net_type == NET_DISCONNECTED:
+                elif e.net_type == net.event.NET_DISCONNECTED:
                     connection_status(screen, (140, 38), None)
                     connection = None
                     messages = {}
                     message_status(screen, (110, 62), messages)
-                elif e.net_type == NET_RECEIVED:
+                elif e.net_type == net.event.NET_RECEIVED:
                     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(messages) < 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 == net.State.CONNECTED:
             msg = ''.join(random.sample('abcdefghijklmnopqrstuvwxyz', 10))
 
             # Sending messages

File test_server.py

 import logging
-import pygame_network
-from pygame_network import Handler, Server
+import pygame_network as net
 
 
-class EchoHandler(Handler):
+class EchoHandler(net.Handler):
     def net_echo(self, channel, message_id, message):
         msg = message.msg.upper()
         self.connection.net_echo(msg)
-        print 'message #%d @ch%d: %s' % (message_id, channel, message)
+        logging.info('message #%d @ch%d: %s', message_id, channel, message)
 
 
 def main():
-    logging.basicConfig(level=logging.DEBUG)
-
-    pygame_network.register('echo', ('msg',))
-    print 'starting server'
-    server = Server(port=54301)
+    net.init(logging_lvl=logging.DEBUG)
+    net.register('echo', ('msg',))
+    server = net.Server(port=54301)
     server.handler_cls = EchoHandler
-    print 'server started'
+    logging.info('Listening')
     run = True
     while run:
         server.step(1000)