Commits

Szymon Wróblewski  committed b10214e

Server class finished, updated tests

  • Participants
  • Parent commits d5070e3

Comments (0)

Files changed (10)

File pygame_network/__init__.py

 import packet
 import client
+import server
 import syncobject
-
-import logging as _logging
-_logging.basicConfig(level=_logging.DEBUG)

File pygame_network/client.py

         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()
-                _logger.info('Connected to %s', event.peer.address)
             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]
-                _logger.info('Disconnected from %s', event.peer.address)
             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)
-                _logger.info('Received data from %s', event.peer.address)
             event = host.check_events()

File pygame_network/connection.py

         self.peer = peer
         self._packet_cnt = 0
         self._packet_manager = packet_manager
-        self._receiver = None
+        self._receivers = []
 
     def __del__(self):
         self.peer.disconnect_now()
     def _receive(self, data, channel):
         packet_id, packet = self._packet_manager.unpack(data)
         _received_event(self, channel, packet, packet_id)
-        if self._receiver is not None:
-            name = 'net_' + packet.__class__.__name__
-            getattr(self._receiver, name, self._receiver.on_recive)(channel, packet_id, packet)
+        name = 'net_' + packet.__class__.__name__
+        for r in self._receivers:
+            getattr(r, name, r.on_recive)(channel, packet_id, packet)
 
     def _connect(self):
         _connected_event(self)
-        if self._receiver is not None:
-            self._receiver.on_connect()
+        for r in self._receivers:
+            r.on_connect()
 
     def _disconnect(self):
         _disconnected_event(self)
-        if self._receiver is not None:
-            self._receiver.on_disconnect()
+        for r in self._receivers:
+            r.on_disconnect()
 
     def disconnect(self):
         self.peer.disconnect()
     def disconnect_later(self):
         self.peer.disconnect_later()
 
+    def add_receiver(self, receiver):
+        self._receivers.append(receiver)
+        receiver.connection = proxy(self)
+
     @property
     def state(self):
         return self.peer.state
 
 
 class Receiver(object):
-    def __init__(self, connection, *args, **kwargs):
-        super(Receiver, self).__init__(*args, **kwargs)
-        connection._receiver = proxy(self)
-        self.connection = connection
-
     def on_connect(self):
         pass
 

File pygame_network/event.py

 NET_RESPONSE = 3  # TODO: response !!
 
 
+def conf_newtwork_event(val=1):
+    global NETWORK
+    NETWORK = USEREVENT + val
+
+
 def _connected_event(connection):
     pygame.event.post(Event(NETWORK, {
         'net_type': NET_CONNECTED,

File pygame_network/packet.py

         self._hash = None
 
     @classmethod
-    def register(cls, name, field_names, channel=0, flags=enet.PACKET_FLAG_RELIABLE):
+    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

File pygame_network/server.py

 import logging
+from weakref import proxy
 import enet
 from packet import PacketManager
-from connection import Connection
+from connection import Connection, Receiver
 
 _logger = logging.getLogger(__name__)
 
 
 class Server(object):
     packet_manager = PacketManager
-    receiver = None
+    receiver_cls = None
 
     def __init__(self, address, port, connections_limit=4, 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.peers = {}
         self._peer_cnt = 0
         self.packet_manager._frozen = True
 
     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:
                 if event.data == self.packet_manager.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)
-                    self._peers[peer_id] = connection
-                    # TODO: add receiver
+                    if issubclass(self.receiver_cls, Receiver):
+                        receiver = self.receiver_cls()
+                        receiver.server = proxy(self)
+                        connection.add_receiver(receiver)
+                    self.peers[peer_id] = connection
                     connection._connect()
-                    _logger.info('Connection with %s accepted', event.peer.address)
                 else:
-                    event.peer.data = 'N'
-                    event.peer.disconnect()
-                    _logger.warning('Connection with %s refused, incompatible packets set', event.peer.address)
+                    _logger.warning('Connection with %s refused, PacketManager'\
+                                    ' hash incorrect', event.peer.address)
+                    event.peer.disconnect_now()
             elif event.type == enet.EVENT_TYPE_DISCONNECT:
-                if event.peer.data != 'N':
-                    self._peers[event.peer.data]._disconnect()
-                    del self._peers[event.peer.data]
                 _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:
-                self._peers[event.peer.data]._receive(event.packet.data, event.channelID)
                 _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 test_client_1.py

 import random
 import logging
-import enet
 import pygame_network
 
-logging.basicConfig(level=logging.DEBUG)
 
-MSG_NUMBER = 10
-SHUTDOWN_MSG = b"SHUTDOWN"
+def main():
+    logging.basicConfig(level=logging.DEBUG)
 
-pygame_network.packet.PacketManager.register('echo', ('msg',))
+    pygame_network.packet.PacketManager.register('echo', ('msg',))
+    pygame_network.packet.PacketManager.register('test')
+    print 'connecting'
+    client = pygame_network.client.Client()
+    connection = client.connect("localhost", 54301)
+    counter = 0
+    print 'client started'
+    while connection.state != pygame_network.connection.STATE_DISCONNECTED:
+        client.step()
+        if counter < 10 and connection.state == pygame_network.connection.STATE_CONNECTED:
+            msg = ''.join(random.sample('abcdefghijklmnopqrstuvwxyz', 10))
+            print("%s: out: %r" % (connection.address, msg))
+            connection.net_echo(msg)
+            counter += 1
 
-print 'connecting'
-client = pygame_network.client.Client()
-connection = client.connect("localhost", 54301)
 
-counter = 0
-print 'client started'
-while connection.state != enet.PEER_STATE_DISCONNECTED:
-    client.step()
-    if counter < MSG_NUMBER and connection.state == enet.PEER_STATE_CONNECTED:
-        msg = ''.join(random.sample('abcdefghijklmnopqrstuvwxyz', 10))
-        print("%s: out: %r" % (connection.address, msg))
-        connection.net_echo(msg)
-        counter += 1
+if __name__ == '__main__':
+    main()

File test_client_2.py

 import logging
 import pygame_network
 
-logging.basicConfig(level=logging.DEBUG)
-
 
 class EchoReceiver(pygame_network.connection.Receiver):
-    def __init__(self, connection):
-        super(EchoReceiver, self).__init__(connection)
+    def __init__(self):
         self.connected = None
         self.counter = 10
 
 
 
 def main():
+    logging.basicConfig(level=logging.DEBUG)
+
     pygame_network.packet.PacketManager.register('echo', ('msg',))
     print 'connecting'
     client = pygame_network.client.Client()
     connection = client.connect("localhost", 54301)
-    receiver = EchoReceiver(connection)
+    receiver = EchoReceiver()
+    connection.add_receiver(receiver)
     print 'client started'
     while receiver.connected != False:
         client.step()

File test_client_3.py

 import pygame_network
 from pygame_network.event import *
 
-logging.basicConfig(level=logging.DEBUG)
-
 
 def packet_status(screen, position, packets):
     i = 0
 
 
 def main():
+    logging.basicConfig(level=logging.DEBUG)
+
     # Pygame init
     pygame.init()
     screen = pygame.display.set_mode((800, 600))

File test_server.py

-import enet
+import logging
 import pygame_network
+from pygame_network.server import Server
+from pygame_network.connection import Receiver
 
-PM = pygame_network.packet.PacketManager
-PM.register('echo', ('msg',))
-PM._frozen = True
 
-host = enet.Host(enet.Address(b"localhost", 54301), 10, 0, 0, 0)
+class EchoReceiver(pygame_network.connection.Receiver):
+    def net_echo(self, channel, packet_id, packet):
+        msg = packet.msg.upper()
+        self.connection.net_echo(msg)
+        print 'packet #%d @ch%d: %s' % (packet_id, channel, packet)
 
-run = True
-connections = {}
-while run:
-    # Wait 1 second for an event
-    event = host.service(1000)
-    if event.type == enet.EVENT_TYPE_CONNECT:
-        correct = event.data == PM.get_hash()
-        print("%s: CONNECT, PacketManager hash %scorrect" % (
-            event.peer.address, '' if correct else 'in'))
-        if correct:
-            connections[event.peer.incomingSessionID] = 0
-        else:
-            event.peer.disconnect()
-    elif event.type == enet.EVENT_TYPE_DISCONNECT:
-        print("%s: DISCONNECT" % event.peer.address)
-    elif event.type == enet.EVENT_TYPE_RECEIVE:
-        pid, packet = PM.unpack(event.packet.data)
-        msg = packet.msg.upper()
-        print("%s: IN:  %r" % (event.peer.address, packet.msg))
-        if event.peer.send(0, enet.Packet(PM.pack(pid, packet.__class__(msg)))) < 0:
-            print("%s: Error sending echo packet!" % event.peer.address)
-        else:
-            print("%s: OUT: %r" % (event.peer.address, msg))
-        connections[event.peer.incomingSessionID] += 1
+
+def main():
+    logging.basicConfig(level=logging.DEBUG)
+
+    pygame_network.packet.PacketManager.register('echo', ('msg',))
+    print 'starting server'
+    server = Server("localhost", 54301)
+    server.receiver_cls = EchoReceiver
+    print 'server started'
+    run = True
+    while run:
+        server.step(1000)
+
+
+if __name__ == '__main__':
+    main()