Commits

Szymon Wróblewski committed 097faeb

extended documentation

Comments (0)

Files changed (11)

doc/source/client.rst

-:mod:`client` Module
-====================
-
-.. module:: client
-   :synopsis: Classes useful for network clients.
-
-
-.. class:: Host([connection])
-
-   Class allowing to send messages and packets.
-   
-   Sending is possible in two ways:
-   
-   * using :samp:`net_{packet_name}` methods, where :samp:`{packet_name}` 
-     is name of packet registered in :class:`~.packet.PacketManager`  
-   * using ``send`` method with packet as argument
-   
-   Example::
-   
-       host = Host()
-       # chat_msg packet is defined in packet module
-       host.net_chat_msg('Tom', 'Test message')
-       # alternative
-       host.send(packet.chat_msg('Tom', 'Test message'))
-   
-   
-   .. attribute:: Host.channel
-   
-      Channel of enet connection
-      
-   
-   .. attribute:: Host.peer
-   
-      Enet connection to send packet over
-      
-   
-   .. method:: Host.send(packet[ , \*args, \*\*kwargs])
-   
-      Send packet to remote host
-      
-      :param packet: 
-         object of class created by :meth:`packet.PacketManager.register` or 
-         name of packet (args and kwargs are used to initialize packet object)
-      :rtype: 
-         (int) packet id which can be used to retrieve response from 
-         Pygame event queue
-      

doc/source/packet.rst

 
    Class allowing to register new packet types and send them.
    
-   It is used by :class:`client.Host` and :class:`syncobject.SyncObjectManager`.
-   Only method useful to user is :meth:'register' 
-   allowing to register new packets.
+   It is used by :class:`Client` and :class:`Server`.
    
    Example::
    
       Returns packet class with given name
    
       :param name: name of packet
-      :rtype: (named tuple) packet
+      :return: packet (namedtuple)
       
    
    .. classmethod:: PacketManager.register(name, field_names[, flags])
       :param flags: 
          enet flags used when sending packet
          (default :const:`enet.PACKET_FLAG_RELIABLE`)
-      :rtype: (named tuple) packet
-      
-   
-   .. classmethod:: PacketManager.send(peer, channel, packet[, *args, **kwargs])
-   
-      Send packet to remote host
-      
-      :param peer: connection to send packet over
-      :param channel: channel of connection
-      :param packet: 
-         object of class created by :meth:`register` or 
-         name of packet (args and kwargs are used to initialize packet object)
-      :rtype: 
-         (int) packet id which can be used to retrieve response from 
-         Pygame event queue
+      :return: packet (namedtuple)
       
 
 Predefined packets

doc/source/pygame_network.rst

 .. toctree::
    :maxdepth: 1
    
-   client
+   connection
+   event
    packet
    syncobject
-   
-Events
-------
-
-Connected event
-   | ``event.type`` = :const:`NETWORK`
-   | ``event.net_type`` = :const:`NET_CONNECTED`
-   | ``event.connection`` -- :func:`proxy <weakref.proxy>` to connection
-
-Disconnected event
-   | ``event.type`` = :const:`NETWORK`
-   | ``event.net_type`` = :const:`NET_DISCONNECTED`
-   | ``event.connection`` -- :func:`proxy <weakref.proxy>` to connection
-
-Received event
-   | ``event.type`` = :const:`NETWORK`
-   | ``event.net_type`` = :const:`NET_RECEIVED`
-   | ``event.connection`` -- :func:`proxy <weakref.proxy>` to connection
-   | ``event.channel`` -- channel of connection
-   | ``event.packet`` -- received packet
-   | ``event.p_id`` -- packet identifier
-   | ``event.p_type`` -- packet type
-
-Response event
-   | ``event.type`` = :const:`NETWORK`
-   | ``event.net_type`` = :const:`NET_RESPONSE`
-   | ``event.connection`` -- :func:`proxy <weakref.proxy>` to connection
-   | ``event.channel`` -- channel of connection
-   | ``event.packet`` -- received packet
-   | ``event.p_id`` -- packet identifier
-   | ``event.p_type`` -- packet type
-
-Example::
-
-   for e in pygame.event.get():
-       if e.type == NETWORK:
-           if e.net_type == NET_CONNECTED:
-               print 'connected'
-           elif e.net_type == NET_DISCONNECTED:
-               print 'disconnected'
-           elif e.net_type == NET_RECEIVED:
-               if e.p_type == packet.chat_msg:
-                   print '%s: %s' % (e.packet.player, e.packet.msg)
-               else:
-                   print 'received:', e.packet
-           elif e.net_type == NET_RESPONSE:
-               print 'response @%d: %s' % (e.p_id, e.packet)
 
 
 Functions
       (default :const:`enet.PACKET_FLAG_RELIABLE`)
    :rtype: (named tuple) packet
    
-   
+   
+.. class:: Client([connections_limit, channel_limit, in_bandwidth, out_bandwidth])
+
+   Class representing network client
+
+   Example::
+   
+      client = pygame_network.Client()
+      connection = client.connect("localhost", 10000)
+      while True:
+         client.step()
+
+
+.. class:: Server([address, port, connections_limit, channel_limit, in_bandwidth, out_bandwidth])
+
+   Class representing network client
+
+   Example::
+   
+      server = pygame_network.Server(port=10000)
+      while True:
+         client.step()
+
+
+.. class:: Receiver()

pygame_network/__init__.py

 import packet
-import client
-import server
 import syncobject
+from client import Client
+from server import Server
+from receiver import Receiver
+
+register = packet.PacketManager.register

pygame_network/client.py

 
 
 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 = {}

pygame_network/connection.py

-from weakref import WeakKeyDictionary, proxy
+__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')
+
+from weakref import proxy
 from functools import partial
 import enet
 from packet import PacketManager
 
 
 class Connection(object):
-    """Class allowing to send messages and packets
+    """Class allowing to send packets
 
-    peer - connection to send packet over
-    channel - channel of connection
+    It's created by by Client or Server, shouldn't be created manually.
 
-    example:
-        client = Client()
-        # chat_msg packet is defined in packets module
-        client.net_chat_msg('Tom', 'Test message')
-        # alternative
-        client.send(packets.chat_msg('Tom', 'Test message'))
+    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
+
+    Attributes:
+        parent - proxy to Client / Server instance
+        peer - Enet peer instance
     """
 
     def __init__(self, parent, peer, packet_manager=PacketManager):
     def send(self, packet, *args, **kwargs):
         """Send packet to remote host
 
-        Client.send(packet, *args, **kwargs): return int
+        Connection.send(packet, *args, **kwargs): return int
 
         packet - class created by PacketManager.register or packet name
 
             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 packets are sent.
+        """
         self.peer.disconnect_later()
 
+    def disconnect_now(self):
+        """Force an immediate disconnection.
+        """
+        self.peer.disconnect_now()
+
     def add_receiver(self, receiver):
+        """Add new Receiver to handle packets.
+
+        Connection.add_receiver(receiver)
+
+        receiver - instance of Receiver subclass
+        """
         self._receivers.append(receiver)
         receiver.connection = proxy(self)
 
     @property
     def state(self):
+        """Connection state."""
         return self.peer.state
 
     @property
     def address(self):
+        """Connection address."""
         return self.peer.address
-
-
-class Receiver(object):
-    def on_connect(self):
-        pass
-
-    def on_disconnect(self):
-        pass
-
-    def on_recive(self, channel, packet_id, packet):
-        pass

pygame_network/event.py

+__all__ = ('NETWORK',
+           'NET_CONNECTED',
+           'NET_DISCONNECTED',
+           'NET_RECEIVED',
+           'NET_RESPONSE')
+
 from weakref import proxy
 import pygame
 from pygame.event import Event
 NET_RESPONSE = 3  # TODO: response !!
 
 
-def conf_newtwork_event(val=1):
+def init(event_val=1):
     global NETWORK
-    NETWORK = USEREVENT + val
+    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_event(connection):
         #'connection': proxy(connection)
         'connection': connection
     }))
-connection._connected_event = _connected_event
 
 
 def _disconnected_event(connection):
         #'connection': proxy(connection)
         'connection': connection
     }))
-connection._disconnected_event = _disconnected_event
 
 
 def _received_event(connection, channel, packet, packet_id):
         'p_id': packet_id,
         'p_type': packet.__class__
     }))
-connection._received_event = _received_event
 
 
 def _response_event(connection, channel, packet, packet_id):
         'p_id': packet_id,
         'p_type': packet.__class__
     }))
-connection._response_event = _response_event

pygame_network/server.py

 import logging
 from weakref import proxy
 import enet
+from receiver import Receiver
 from packet import PacketManager
-from connection import Connection, Receiver
+from connection import Connection
 
 _logger = logging.getLogger(__name__)
 
     packet_manager = PacketManager
     receiver_cls = None
 
-    def __init__(self, address, port, connections_limit=4, channel_limit=0, in_bandwidth=0, out_bandwidth=0):
+    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.host = enet.Host(address, connections_limit, channel_limit,
+                              in_bandwidth, out_bandwidth)
         self.peers = {}
         self._peer_cnt = 0
         self.packet_manager._frozen = True
 import random
 import logging
 import pygame_network
+from pygame_network.connection import STATE_CONNECTED, STATE_DISCONNECTED
 
 
 def main():
     logging.basicConfig(level=logging.DEBUG)
 
-    pygame_network.packet.PacketManager.register('echo', ('msg',))
+    pygame_network.register('echo', ('msg',))
     print 'connecting'
-    client = pygame_network.client.Client()
+    client = pygame_network.Client()
     connection = client.connect("localhost", 54301)
     counter = 0
     print 'client started'
-    while connection.state != pygame_network.connection.STATE_DISCONNECTED:
+    while connection.state != STATE_DISCONNECTED:
         client.step()
-        if counter < 10 and connection.state == pygame_network.connection.STATE_CONNECTED:
+        if counter < 10 and connection.state == STATE_CONNECTED:
             msg = ''.join(random.sample('abcdefghijklmnopqrstuvwxyz', 10))
             print("%s: out: %r" % (connection.address, msg))
             connection.net_echo(msg)
 import random
 import logging
 import pygame_network
+from pygame_network import Receiver, Client
 
 
-class EchoReceiver(pygame_network.connection.Receiver):
+class EchoReceiver(Receiver):
     def __init__(self):
         self.connected = None
         self.counter = 10
 def main():
     logging.basicConfig(level=logging.DEBUG)
 
-    pygame_network.packet.PacketManager.register('echo', ('msg',))
+    pygame_network.register('echo', ('msg',))
     print 'connecting'
-    client = pygame_network.client.Client()
+    client = Client()
     connection = client.connect("localhost", 54301)
     receiver = EchoReceiver()
     connection.add_receiver(receiver)
 import logging
 import pygame_network
-from pygame_network.server import Server
-from pygame_network.connection import Receiver
+from pygame_network import Receiver, Server
 
 
-class EchoReceiver(pygame_network.connection.Receiver):
+class EchoReceiver(Receiver):
     def net_echo(self, channel, packet_id, packet):
         msg = packet.msg.upper()
         self.connection.net_echo(msg)
 def main():
     logging.basicConfig(level=logging.DEBUG)
 
-    pygame_network.packet.PacketManager.register('echo', ('msg',))
+    pygame_network.register('echo', ('msg',))
     print 'starting server'
-    server = Server("localhost", 54301)
+    server = Server(port=54301)
     server.receiver_cls = EchoReceiver
     print 'server started'
     run = True