Commits

Szymon Wróblewski committed 7ede2cd

added temporary network modules

  • Participants
  • Parent commits b4d4631

Comments (0)

Files changed (2)

alchemymadness/network_tmp/client.py

+import sys
+from threading import Thread, Event
+from PodSixNet.Connection import ConnectionListener, connection
+
+class RemoteObject(object):
+    synch = ()
+    
+    def __init__(self):
+        self.changed = False
+        self.updating = Event()
+        self.__setattr__ = self._setattr
+    
+    def _synch_var(self):
+        return ((k,v) for k,v in self.__dict__.iteritems() if k in self.synch)
+        
+    def _setattr(self, name, value):
+        object.__setattr__(self, name, value)
+        if not self.updating.is_set():
+            object.__setattr__(self, '_changed', self.changed or name in self.synch)
+
+class Player(RemoteObject):
+    synch = ('test',)
+    def __init__(self):
+        super(Player, self).__init__()
+        self.test = 'aaa'
+
+class GameClient(ConnectionListener):
+    def __init__(self, host, port):
+        self.player = Player()
+        self.others = {}
+        self._stop = Event()
+        self.input_thread = Thread(target = self.input_handler)
+        self.input_thread.daemon = True
+        self.input_thread.start()
+        self.Connect((host, port))
+        
+    def step(self, *args):
+        connection.Pump()
+        if self.player.changed:
+            self.Send(dict(self.player._synch_var(), action='update'))
+            self.player.changed = False
+        self.Pump()
+        
+    #def Network(self, data):
+    #    print data
+        
+    def Network_connected(self, data):
+        print '# Connected'
+        self._stop.clear()
+        if not self.input_thread.is_alive():
+            self.input_thread.start()
+
+    def Network_error(self, data):
+        print '# Error:', data['error'][1]
+        self.connection.Close()
+        self._stop.set()
+
+    def Network_disconnected(self, data):
+        print '# Disconnected'
+        self._stop.set()
+        
+    def Network_info(self, data):
+        for msg in data['info'].split('/n'):
+            print '#', msg
+        
+    def Network_msg(self, data):
+        print '%s: %s' % (data['id'], data['msg'])
+        
+    def Network_init(self, data):
+        self.player.updating.set()
+        self.player.test = data['test']
+        self.player.updating.clear()
+        
+    def Network_add(self, data):
+        p = Player()
+        self.others[data['id']] = p
+        
+    def Network_del(self, data):
+        del self.others[data['id']]
+        
+    def Network_update(self, data):
+        p = self.others[data['id']]
+        del data['action']
+        p.test = data['test']
+    
+    def input_handler(self):
+        while not self._stop.is_set():
+            msg = raw_input()
+            if len(msg) > 0:
+                self.Send({'action': 'msg', 'msg': msg[:255]})
+                
+    def run(self):
+        while not self._stop.wait(0.001):
+            self.step()
+
+if __name__ == '__main__':
+    addr = 'localhost'
+    if len(sys.argv) > 1:
+        addr = sys.argv[1]
+    GameClient(addr, 10000).run()

alchemymadness/network_tmp/server.py

+from weakref import WeakKeyDictionary
+from threading import Thread, Timer, Event
+from PodSixNet.Server import Server
+from PodSixNet.Channel import Channel
+
+MAX_CLIENTS = 4
+
+class ClientChannel(Channel):
+    def __init__(self, *args, **kwargs):
+        Channel.__init__(self, *args, **kwargs)
+        self.id = -1
+        self.data = {'test': 123}
+        self._server.add_player(self)
+    
+    def Network(self, data):
+        print data
+        
+    def Network_update(self, data):
+        del data['action']
+        self.data = data
+        self._server.send_to_all(dict(data, action='update', id=self.id), self)
+        
+    def Network_msg(self, data):
+        self._server.send_to_all({'action':'msg', 'id':self.id, 'msg':data['msg']}, self)
+
+    def Close(self):
+        self._server.del_player(self)
+
+class GameServer(Server):
+    channelClass = ClientChannel
+    
+    def __init__(self, port, *args, **kwargs):
+        Server.__init__(self, localaddr=('', port), *args, **kwargs)
+        self.players = WeakKeyDictionary()
+        self._stop = Event()
+        self.av_id = 0
+
+    def Connected(self, channel, addr):
+        print 'New connection:', channel
+        
+    def add_player(self, player):
+        if len(self.players) >= MAX_CLIENTS:
+            player.Send({'action':'info', 'info':'Server full'})
+            player.Pump()
+            player.close()
+            return
+        else:
+            player.id = self.av_id
+            self.av_id += 1
+            print 'New player #%d (%s:%s)' % (player.id, player.addr[0], player.addr[0])
+            player.Send(dict(player.data, action='init'))
+            for p in self.players:
+                player.Send({'action':'add', 'id':p.id})
+            player.Pump()            
+            self.send_to_all({'action':'add', 'id':player.id}, player)
+            self.players[player] = True
+
+    def del_player(self, player):
+        print 'Deleting player @ %s:%s' % player.addr
+        if self.players.has_key(player):
+            self.send_to_all({'action': 'del', 'id':player.id}, player)
+            del self.players[player]
+    
+    def send_to_all(self, data, exclude=None):
+        for p in self.players:
+            if not p is exclude:
+                p.Send(data)
+        
+    def run(self):
+        while not self._stop.wait(0.001):
+            self.Pump()
+        
+if __name__ == "__main__":
+    print "serving @10000"
+    GameServer(10000).run()