Commits

Szymon Wróblewski committed e695fc5

updated adapters

Comments (0)

Files changed (10)

pygame_network/event.py

     pass
 
 
-def received(connection, message, channel):
+def received(connection, message):
     pass
 
 
             'net_type': NET_RECEIVED,
             #'connection': proxy(connection),
             'connection': connection,
-            'channel': channel,
             'message': message,
             'msg_type': message.__class__
         }))

pygame_network/handler.py

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

pygame_network/network/base_adapter.py

 from functools import partial
 from .. import message
 from .. import event
+from ..handler import Handler
 
 __all__ = ('Connection', 'State')
 _logger = logging.getLogger(__name__)
       is name of message registered in MessageFactory
     * using send method with message as argument
 
+    Attributes:
+        parent - proxy to Client / Server instance
+        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
     """
-    message_factory = message.message_factory
 
-    def __init__(self, parent, message_factory=None, *args, **kwargs):
+    def __init__(self, parent, message_factory, *args, **kwargs):
         super(Connection, self).__init__(*args, **kwargs)
         self.parent = proxy(parent)
-        if message_factory is not None:
-            self.message_factory = message_factory
+        self.message_factory = message_factory
         self.message_factory.reset_context(self)
-        self._handlers = []
+        self.handlers = []
         self.data_sent = 0
         self.data_received = 0
         self.messages_sent = 0
         self.messages_sent += 1
         return self._send_data(data, **params)
 
-    def _receive(self, data, channel=0):
+    def _receive(self, data, **kwargs):
         for message in self.message_factory.unpack_all(data, self):
             name = message.__class__.__name__
             _logger.info('Received %s message from %s:%s', name, *self.address)
-            event.received(self, message, channel)
-            for h in self._handlers:
-                getattr(h, 'net_' + name, h.on_recive)(message, channel)
+            event.received(self, message)
+            for h in self.handlers:
+                getattr(h, 'net_' + name, h.on_recive)(message, **kwargs)
 
     def _connect(self):
         _logger.info('Connected to %s:%s', *self.address)
         event.connected(self)
-        for h in self._handlers:
+        for h in self.handlers:
             h.on_connect()
 
     def _disconnect(self):
         _logger.info('Disconnected from %s:%s', *self.address)
         event.disconnected(self)
-        for h in self._handlers:
+        for h in self.handlers:
             h.on_disconnect()
 
     def disconnect(self, *args):
 
         handler - instance of Receiver subclass
         """
-        self._handlers.append(handler)
+        self.handlers.append(handler)
         handler.connection = proxy(self)
 
     @property
 class Server(object):
     message_factory = message.message_factory
     handler = None
+    connection = Connection
 
-    def __init__(self, address='', port=0, connections_limit=4, *args, **kwargs):
-        _logger.debug('Server created %s, connections limit: %d', address, connections_limit)
+    def __init__(self, address='', port=0, conn_limit=4, *args, **kwargs):
+        super(Server, self).__init__(*args, **kwargs)
+        _logger.info('Server created %s:%d, connections limit: %d', address, port, conn_limit)
         self.message_factory.set_frozen()
-        _logger.debug('MessageFactory frozen')
         self.conn_map = {}
 
-    def step(self, timeout=0):
+    def update(self, timeout=0):
         pass
 
+    def _accept(self, mf_hash, socket, c_id, address):
+        if mf_hash == self.message_factory.get_hash():
+            _logger.info('Connection with %s accepted', address)
+            connection = self.connection(self, socket, self.message_factory)
+            if self.handler is not None and issubclass(self.handler, Handler):
+                handler = self.handler()
+                handler.server = proxy(self)
+                connection.add_handler(handler)
+            self.conn_map[c_id] = connection
+            event.accepted(self)
+            connection._connect()
+            return True
+        else:
+            _logger.info('Connection with %s refused, MessageFactory'\
+                            ' hash incorrect', address)
+            return False
+
+    def _disconnect(self, c_id):
+        self.conn_map[c_id]._disconnect()
+        del self.conn_map[c_id]
+
+    def _receive(self, c_id, data, **kwargs):
+        self.conn_map[c_id]._receive(data, **kwargs)
+
     def connections(self, exclude=None):
         if exclude is None:
             return self.conn_map.itervalues()
 
     def handlers(self, exclude=None):
         if exclude is None:
-            return (c._handlers[0] for c in self.conn_map.itervalues())
+            return (c.handlers[0] for c in self.conn_map.itervalues())
         else:
-            return (c._handlers[0] for c in self.conn_map.itervalues() if c not in exclude)
+            return (c.handlers[0] for c in self.conn_map.itervalues() if c not in exclude)
 
+
+class Client(object):
+    """Class representing network client
+
+    Example:
+        client = pygame_network.client.Client()
+        connection = client.connect("localhost", 10000)
+        while True:
+            client.update()
+    """
+    message_factory = message.message_factory
+
+    def __init__(self, conn_limit=1, *args, **kwargs):
+        super(Client, self).__init__(*args, **kwargs)
+        self.conn_map = {}
+        _logger.info('Client created, connections limit: %d', conn_limit)
+
+    def connect(self, address, port, message_factory=None, **kwargs):
+        if message_factory is None:
+            message_factory = self.message_factory
+        _logger.info('Connecting to %s:%d', address, port)
+        message_factory.set_frozen()
+        socket, c_id = self._create_connection(address, port, message_factory.get_hash(), **kwargs)
+        conn = self.connection(self, socket, message_factory)
+        self.conn_map[c_id] = conn
+        return conn
+
+    def update(self, timeout=0):
+        pass
+
+    def _connect(self, c_id):
+        self.conn_map[c_id]._connect()
+
+    def _disconnect(self, c_id):
+        self.conn_map[c_id]._disconnect()
+        del self.conn_map[c_id]
+
+    def _receive(self, c_id, data, **kwargs):
+        self.conn_map[c_id]._receive(data, **kwargs)

pygame_network/network/enet_adapter/client.py

 import logging
 import enet
-from ... import message
+from .. import base_adapter
 from connection import Connection
 
 _logger = logging.getLogger(__name__)
 
 
-class Client(object):
-    """Class representing network client
+class Client(base_adapter.Client):
+    connection = Connection
 
-    Example:
-        client = pygame_network.client.Client()
-        connection = client.connect("localhost", 10000)
-        while True:
-            client.step()
-    """
-    def __init__(self, connections_limit=1, *args, **kwargs):
+    def __init__(self, conn_limit=1, *args, **kwargs):
         super(Client, self).__init__(*args, **kwargs)
-        self.host = enet.Host(None, connections_limit)
-        self._peers = {}
+        self.host = enet.Host(None, conn_limit)
         self._peer_cnt = 0
-        _logger.debug('Client created, connections limit: %d', connections_limit)
 
-    def connect(self, address, port, channels=2, message_factory=message.message_factory):
+    def _create_connection(self, address, port, mf_hash, channels=1, **kwargs):
         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.set_frozen()
-        _logger.debug('MessageFactory frozen')
-        peer = self.host.connect(address, channels, message_factory.get_hash())
+        peer = self.host.connect(address, channels, mf_hash)
         peer.data = peer_id
-        connection = Connection(self, peer, message_factory)
-        self._peers[peer_id] = connection
-        return connection
+        return peer, peer_id
 
-    def step(self, timeout=0):
-        if len(self._peers) == 0:
+    def update(self, timeout=0):
+        if len(self.conn_map) == 0:
             return
         host = self.host
         event = host.service(timeout)
         while event is not None:
             if event.type == enet.EVENT_TYPE_CONNECT:
-                self._peers[event.peer.data]._connect()
+                self._connect(event.peer.data)
             elif event.type == enet.EVENT_TYPE_DISCONNECT:
-                self._peers[event.peer.data]._disconnect()
-                del self._peers[event.peer.data]
+                self._disconnect(event.peer.data)
             elif event.type == enet.EVENT_TYPE_RECEIVE:
-                self._peers[event.peer.data]._receive(event.packet.data, event.channelID)
+                self._receive(event.peer.data, event.packet.data, channel=event.channelID)
             event = host.check_events()

pygame_network/network/enet_adapter/connection.py

 
 
 class Connection(base_adapter.Connection):
-    """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=None):
-        super(Connection, self).__init__(parent, message_factory)
+    def __init__(self, parent, peer, message_factory, *args, **kwargs):
+        super(Connection, self).__init__(parent, message_factory, *args, **kwargs)
         self.peer = peer
 
     def __del__(self):
         self.peer.disconnect_now()
 
-    def _send_data(self, data, channel=0, flags=enet.PACKET_FLAG_RELIABLE):
+    def _send_data(self, data, channel=0, flags=enet.PACKET_FLAG_RELIABLE, **kwargs):
         self.peer.send(channel, enet.Packet(data, flags))
 
     def disconnect(self, when=0):
 
         when - type of disconnection
                0  - disconnect with acknowledge
-               -1 - disconnect after sending all messages
-               1  - disconnect without acknowledge
+               1  - disconnect after sending all messages
+               -1 - disconnect without acknowledge
         """
         if when == 0:
             self.peer.disconnect()
-        elif when == -1:
+        elif when == 1:
             self.peer.disconnect_later()
         else:
             self.peer.disconnect_now()

pygame_network/network/enet_adapter/server.py

 import logging
-from weakref import proxy
 import enet
-from ...handler import Handler
 from ... import message
+from .. import base_adapter
 from connection import Connection
 
 _logger = logging.getLogger(__name__)
 
 
-class Server(object):
-    message_factory = message.message_factory
-    handler = None
+class Server(base_adapter.Server):
+    connection = Connection
 
     def __init__(self, address='', port=0, con_limit=4, *args, **kwargs):
-        super(Server, self).__init__(*args, **kwargs)
+        super(Server, self).__init__(address, port, con_limit, *args, **kwargs)
         address = enet.Address(address, port)
         self.host = enet.Host(address, con_limit, *args, **kwargs)
-        self.conn_map = {}
         self._peer_cnt = 0
-        _logger.debug('Server created %s, connections limit: %d', address, con_limit)
-        self.message_factory.set_frozen()
-        _logger.debug('MessageFactory frozen')
 
-
-    def step(self, timeout=0):
+    def update(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)
+                peer_id = str(self._peer_cnt + 1)
+                if self._accept(event.data, event.peer, peer_id, event.peer.address):
                     event.peer.data = peer_id
-                    connection = Connection(self, event.peer, self.message_factory)
-                    if self.handler is not None and issubclass(self.handler, Handler):
-                        handler = self.handler()
-                        handler.server = proxy(self)
-                        connection.add_handler(handler)
-                    self.conn_map[peer_id] = connection
-                    connection._connect()
+                    self._peer_cnt += 1
                 else:
-                    _logger.warning('Connection with %s refused, MessageFactory'\
-                                    ' hash incorrect', event.peer.address)
                     event.peer.disconnect_now()
             elif event.type == enet.EVENT_TYPE_DISCONNECT:
-                self.conn_map[event.peer.data]._disconnect()
-                del self.conn_map[event.peer.data]
+                self._disconnect(event.peer.data)
             elif event.type == enet.EVENT_TYPE_RECEIVE:
-                self.conn_map[event.peer.data]._receive(event.packet.data, event.channelID)
+                self._receive(event.peer.data, event.packet.data, channel=event.channelID)
             event = host.check_events()
-
-    def connections(self, exclude=None):
-        if exclude is None:
-            return self.conn_map.itervalues()
-        else:
-            return (c for c in self.conn_map.itervalues() if c not in exclude)
-
-    def handlers(self, exclude=[]):
-        return (c._handlers[0] for c in self.conn_map.itervalues() if c not in exclude)

pygame_network/network/socket_adapter/connection.py

 import asyncore
 from collections import deque
 from .. import base_adapter
-from ...message import MessageFactory
 
 _logger = logging.getLogger(__name__)
 
     # maximum amount of data received / sent at once
     recv_buffer_size = 4096
 
-    def __init__(self, parent, socket, message_factory=MessageFactory):
-        super(Connection, self).__init__(parent, message_factory)
+    def __init__(self, parent, socket, message_factory, *args, **kwargs):
+        super(Connection, self).__init__(
+            parent, message_factory, # params for base_adapter.Connection
+            socket, parent.conn_map, # params for asyncore.dispatcher
+            * args, **kwargs)
         #self.send_queue = deque()
         self.send_buffer = bytearray()
         self.recv_buffer = bytearray(b'\0' * self.recv_buffer_size)
         self._connect()
 
     def handle_close(self):
-        self.log_info('unhandled close event', 'warning')
+        self._disconnect()
         self.close()
 
     def log_info(self, message, type='info'):
         return getattr(_logger, type)(message)
 
     def disconnect(self, *args):
-        """Request a disconnection."""
         pass
 
     @property
     def address(self):
-        """Connection address."""
-        return self.getpeername()
+        return self.addr
         self.out_counter = 0
         self.in_counter = 0
 
-    def net_echo(self, message, channel):
+    def net_echo(self, message, **kwargs):
+        channel = kwargs.get('channel', 0)
         logging.info('Received message @ch%d: %s', channel, message)
         self.in_counter += 1
 
-    def step(self):
+    def update(self):
         if self.out_counter < 10 and self.connection.connected:
             msg = ''.join(random.sample('abcdefghijklmnopqrstuvwxyz', 10))
             logging.info('Sending: %s', msg)
     handler = EchoHandler()
     connection.add_handler(handler)
     while True:
-        client.step()
-        handler.step()
+        client.update()
+        handler.update()
 
 
 if __name__ == '__main__':
 
             messages[m_id] = [msg, None]
             message_status(screen, (110, 62), messages)
-        client.step()
+        client.update()
         pygame.display.flip()
         if limit:
             clock.tick(4)
 
 
 class EchoHandler(net.Handler):
-    def net_echo(self, message, channel):
+    def net_echo(self, message, **kwargs):
+        channel = kwargs.get('channel', 0)
         logging.info('Received message @ch%d: %s', channel, message)
         msg = message.msg.upper()
         self.connection.net_echo(msg, message.msg_id)
     logging.info('Listening')
     run = True
     while run:
-        server.step(1000)
+        server.update(1000)
 
 
 if __name__ == '__main__':