Ejemplo n.º 1
0
 def main(self):
     """Main (thread) loop"""
     try:
         self.send("Thread running", "signal")
         try:
             sock = socket.socket(socket.AF_INET,
                                  socket.SOCK_STREAM)  #; yield 0.3
         except socket.error, e:
             #handle initial failure to create socket.
             # If we can't create a socket we might as well give up now.
             # This matches the behaviour of the main TCP client but it might be better passing as
             # an Axon.Ipc.errorInformation carrying the exception otherwise what is the IPC class
             # for?
             self.send(e, "signal")
             # I am assuming that by using queues there are no race conditions between this operations.
             self.send(socketShutdown(), "signal")
             return
         self.send("socket object created", "signal")
         try:
             sock.connect((self.host, self.port))
         except socket.error, e:
             self.send(e, "signal")
             try:
                 result = sock.close()
             except:
                 pass
             self.send(socketShutdown(), "signal")
             return
Ejemplo n.º 2
0
 def main(self):
   """Main (thread) loop"""
   try:
    self.send("Thread running","signal")
    try:
       sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)#; yield 0.3
    except socket.error, e:
       #handle initial failure to create socket.
       # If we can't create a socket we might as well give up now.
       # This matches the behaviour of the main TCP client but it might be better passing as
       # an Axon.Ipc.errorInformation carrying the exception otherwise what is the IPC class
       # for?
       self.send(e,"signal")
       # I am assuming that by using queues there are no race conditions between this operations.
       self.send(socketShutdown(),"signal")
       return
    self.send("socket object created","signal")
    try:
       sock.connect((self.host, self.port))
    except socket.error, e:
       self.send(e,"signal")
       try:
          result = sock.close()
       except:
          pass
       self.send(socketShutdown(),"signal")
       return
Ejemplo n.º 3
0
    def handleClosedCSA(self, shutdownCSAMessage):
        """
        handleClosedCSA(shutdownCSAMessage) -> None

        Terminates and unwires the protocol handler for the closing socket.

        Keyword arguments:
        shutdownCSAMessage -- shutdownCSAMessage.object is the ConnectedSocketAdapter for socket that is closing.
        """
        connectedSocket = shutdownCSAMessage.object
        try:
            bundle = self.retrieveTrackedResourceInformation(connectedSocket)
        except KeyError:
            # This means we've actually already done this...
            return
        resourceInboxes, resourceOutboxes, (protocolHandler, controllink) = bundle

        self.connectedSockets = [x for x in self.connectedSockets if x != self.connectedSockets]

        self.unlink(thelinkage=controllink)

        self.send(socketShutdown(), resourceOutboxes[0])  # This is now instantly delivered
        self.send(shutdownMicroprocess(), resourceOutboxes[1])  # This is now instantly delivered

        self.removeChild(connectedSocket)
        self.removeChild(protocolHandler)
        self.deleteOutbox(resourceOutboxes[0])  # So this is now safe
        # This did not used to be the case.
        self.deleteOutbox(resourceOutboxes[1])  # So this is now safe
        # This did not used to be the case.
        self.ceaseTrackingResource(connectedSocket)
Ejemplo n.º 4
0
    def handleClosedCSA(self, shutdownCSAMessage):
        """
        handleClosedCSA(shutdownCSAMessage) -> None

        Terminates and unwires the protocol handler for the closing socket.

        Keyword arguments:
        shutdownCSAMessage -- shutdownCSAMessage.object is the ConnectedSocketAdapter for socket that is closing.
        """
        #        print (shutdownCSAMessage)
        #        print (shutdownCSAMessage.object)
        connectedSocket = shutdownCSAMessage.object
        #        print ("CLOSING", connectedSocket)
        try:
            bundle = self.retrieveTrackedResourceInformation(connectedSocket)
#            print ("BUNDLE", bundle)
        except KeyError:
            # This means we've actually already done this...
            return
        resourceInboxes, resourceOutboxes, (protocolHandler,
                                            controllink) = bundle
        #        print (bundle)

        self.connectedSockets = [
            x for x in self.connectedSockets if x != connectedSocket
        ]

        if controllink:
            self.unlink(thelinkage=controllink)
#        else:
#            print ("Control Link is null, not unlinking")

        self.send(socketShutdown(),
                  resourceOutboxes[0])  # This is now instantly delivered
        self.send(shutdownMicroprocess(),
                  resourceOutboxes[1])  # This is now instantly delivered

        self.removeChild(connectedSocket)
        self.removeChild(protocolHandler)
        self.deleteOutbox(resourceOutboxes[0])  # So this is now safe
        # This did not used to be the case.
        self.deleteOutbox(resourceOutboxes[1])  # So this is now safe
        # This did not used to be the case.
        #        print ("CEASING TRACKING", self._resourceStore)
        self.ceaseTrackingResource(connectedSocket)
Ejemplo n.º 5
0
   def main(self):
     """Main (thread) loop"""
     try:
      self.send("Thread running","signal")
      try:
         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)#; yield 0.3
      except socket.error:
         e = sys.exc_info()[1]
         #handle initial failure to create socket.
         # If we can't create a socket we might as well give up now.
         # This matches the behaviour of the main TCP client but it might be better passing as
         # an Axon.Ipc.errorInformation carrying the exception otherwise what is the IPC class
         # for?
         self.send(e,"signal")
         # I am assuming that by using queues there are no race conditions between this operations.
         self.send(socketShutdown(),"signal")
         return
      self.send("socket object created","signal")
      try:
         sock.connect((self.host, self.port))
      except socket.error:
         e = sys.exc_info()[1]
         self.send(e,"signal")
         try:
            result = sock.close()
         except:
            pass
         self.send(socketShutdown(),"signal")
         return
      self.send("socket connected","signal")
      
      producerFinished = 0
      if self.sendmessage != None:
        try:
            sock.send(self.sendmessage)
        except socket.error:
            e = sys.exc_info()[1]
            self.send(e,"signal")
            try:
                result = sock.close()
            except:
                pass
            self.send(socketShutdown(), "signal")
            return
      # This loop will handle sending, control and signal communications
      # including with the recv thread.  Apart from the sending all the calls
      # should be non-blocking.  sending should rarely take a significant
      # time.  One non-blocking call will operate with a short timeout to
      # prevent busy wait taking too much CPU time.
      while 1:
            try:
               data = sock.recv(1024)
               if not data: # This implies the connection has barfed.
                  break
               self.send(data)
#             except socket.timeout, to:
#               pass # common case Try again next loop.
            except socket.error:
               err = sys.exc_info()[1]
               self.send(err,"signal")
               break # The task is finished now.
         
            try:
               if self.dataReady("control"):
                    msg = self.recv("control")
                    if isinstance(msg, Axon.Ipc.producerFinished):
                        break
                        # Want to give opportunity for inbox messages to get into the
                        # inbox queue before shutting down the sending system.
            except Empty:
               e = sys.exc_info()[1]
               pass # Normal case.
      
      #end while 1
      
      # After breaking out of while loop clean up socket before ending the thread.
      try:
         sock.shutdown(2)
      except socket.error:
         e = sys.exc_info()[1]
         pass
      try:
         sock.close()
      except socket.error:
         e = sys.exc_info()[1]
         self.send(e,"signal")
      self.send(socketShutdown(),"signal")
      #Normal exit
     except Exception:
      e = sys.exc_info()[1]
      self.send("Unexpected exception","signal")
      self.send(e,"signal")
      self.send(socketShutdown(),"signal")
Ejemplo n.º 6
0
 def passOnShutdown(self):
     self.send(socketShutdown(self, [self.socket, self.howDied]),
               "CreatorFeedback")
     self.send(shutdownCSA(self, (self, self.socket)), "signal")
Ejemplo n.º 7
0
                        # inbox queue before shutting down the sending system.
            except Empty, e:
               pass # Normal case.
      
      #end while 1
      
      # After breaking out of while loop clean up socket before ending the thread.
      try:
         sock.shutdown(2)
      except socket.error, e:
         pass
      try:
         sock.close()
      except socket.error, e:
         self.send(e,"signal")
      self.send(socketShutdown(),"signal")
      #Normal exit
     except Exception, e:
      self.send("Unexpected exception","signal")
      self.send(e,"signal")
      self.send(socketShutdown(),"signal")
      #Unhandled exception exit.  Reports via the signal outqueue as it can't print errors here.

__kamaelia_components__  = ( ThreadedTCPClient, )


if __name__ =="__main__":
   from Axon.Scheduler import scheduler
   from Kamaelia.Util.Console import ConsoleEchoer
   from Axon.Ipc import newComponent
   from Kamaelia.Chassis.ConnectedServer import SimpleServer
Ejemplo n.º 8
0
class ThreadedTCPClient(Axon.ThreadedComponent.threadedcomponent):
    """\
   ThreadedTCPClient(host,port[,chargen][,initalsendmessage]) -> threaded component with a TCP connection to a server.

   Establishes a TCP connection to the specified server.
   
   Keyword arguments:
   
   - host     -- address of the server to connect to (string)
   - port     -- port number to connect on
   - initialsendmessage  -- to be send immediately after connection is established (default=None)
   """
    Inboxes = {
        "inbox": "data to send to the socket",
        "control": "",
    }
    Outboxes = {
        "outbox": "data received from the socket",
        "signal": "diagnostic output, errors and shutdown messages",
    }

    def __init__(self, host, port, chargen=0, initialsendmessage=None):
        """x.__init__(...) initializes x; see x.__class__.__doc__ for signature"""
        super(ThreadedTCPClient, self).__init__()
        self.host = host
        self.port = port
        self.chargen = chargen
        self.sendmessage = initialsendmessage

    def main(self):
        """Main (thread) loop"""
        try:
            self.send("Thread running", "signal")
            try:
                sock = socket.socket(socket.AF_INET,
                                     socket.SOCK_STREAM)  #; yield 0.3
            except socket.error, e:
                #handle initial failure to create socket.
                # If we can't create a socket we might as well give up now.
                # This matches the behaviour of the main TCP client but it might be better passing as
                # an Axon.Ipc.errorInformation carrying the exception otherwise what is the IPC class
                # for?
                self.send(e, "signal")
                # I am assuming that by using queues there are no race conditions between this operations.
                self.send(socketShutdown(), "signal")
                return
            self.send("socket object created", "signal")
            try:
                sock.connect((self.host, self.port))
            except socket.error, e:
                self.send(e, "signal")
                try:
                    result = sock.close()
                except:
                    pass
                self.send(socketShutdown(), "signal")
                return
            self.send("socket connected", "signal")

            producerFinished = 0
            if self.sendmessage != None:
                try:
                    sock.send(self.sendmessage)
                except socket.error, e:
                    self.send(e, "signal")
                    try:
                        result = sock.close()
                    except:
                        pass
                    self.send(socketShutdown(), "signal")
                    return
Ejemplo n.º 9
0
                            # inbox queue before shutting down the sending system.
                except Empty, e:
                    pass  # Normal case.

            #end while 1

            # After breaking out of while loop clean up socket before ending the thread.
            try:
                sock.shutdown(2)
            except socket.error, e:
                pass
            try:
                sock.close()
            except socket.error, e:
                self.send(e, "signal")
            self.send(socketShutdown(), "signal")
            #Normal exit
        except Exception, e:
            self.send("Unexpected exception", "signal")
            self.send(e, "signal")
            self.send(socketShutdown(), "signal")
            #Unhandled exception exit.  Reports via the signal outqueue as it can't print errors here.

__kamaelia_components__ = (ThreadedTCPClient, )

if __name__ == "__main__":
    from Axon.Scheduler import scheduler
    from Kamaelia.Util.Console import ConsoleEchoer
    from Axon.Ipc import newComponent
    from Kamaelia.Chassis.ConnectedServer import SimpleServer
    from Kamaelia.Protocol.FortuneCookieProtocol import FortuneCookieProtocol
Ejemplo n.º 10
0
 def passOnShutdown(self):
      self.send(socketShutdown(self,[self.socket,self.howDied]), "CreatorFeedback")
      self.send(shutdownCSA(self, (self,self.socket)), "signal")