Bidirectional Networking

James Mills prologic at shortcircuit.net.au
Sat Dec 13 01:08:45 CET 2008


Just as a matter of completeness for my own suggestion, here
is my implementation of your code (using circuits):

cheers
James

--------------------------

import random
from circuits import listener, Event, Manager
from circuits.lib.sockets import TCPServer, TCPClient

class Server(TCPServer):

   channel = "server"

   @listener("read")
   def onREAD(self, sock, data):
      print "-> RECV: %s - Sent by: %s" % (data, hsot)

class Client(TCPClient):

   channel = "client"

   def __init__(self, remoteServer):
      super(Client, self).__init__()
      self.cycle = 0
      self.randomNumber = 0
      self.message = None
      self.remoteServer = remoteServer

   @listener("connect")
   def onCONNECT(self, host, port):
      self.write(self.message)
      print "SENT ->: %d by by local cycle %d" % (self.randomNumber, self.cycle)
      self.close()
      self.success = True

   @listener("disconnect")
   def onDISCONNECT(self):
      if not self.success:
         print "Failed to send number on cycle %d " % self.cycle
         self.success = None

   @listener("cycle")
   def onCYCLE(self):
      if self.cycle < 1000:
         chance = random.random()

         if (chance < 0.01):
            self.randomNumber = int(random.random() * 1000)
            self.message = "%d from remote cycle %d" % (self.randomNumber,
                  self.cycle)
            self.open(*self.remoteServer)
            self.cycle += 1

         manager.push(Event(), "cycle", "client")

localServer = (9999, "localhost")
remoteServer = ("localhost", 10000)

manager = Manager()

server = Server(*localServer)
client = Client(remoteServer)

manager += server
manager += client

manager.push(Event(), "cycle", "client")

while True:
   try:
      server.poll()
      client.poll()
      manager.flush()
   except KeyboardInterrupt:
      client.close()
      break



More information about the Python-list mailing list