[Twisted-Python] Communicating between listeners

exarkun at divmod.com exarkun at divmod.com
Wed Sep 29 13:28:30 EDT 2004

On Wed, 29 Sep 2004 16:22:32 +0100, tom dyson <tom.dyson at torchbox.com> wrote:
>I'm new to Twisted, and network programming in general. Can anyone 
> provide an example that might help me code the following functionality:
> * Server listens on two ports, one TCP, one UDP
> * Incoming UDP datagrams contain an identifying string
> * A message is broadcast to all connected TCP clients whose username 
> matches the UDP ID.
> In particular, I can't work out how to access details of the current 
> TCP clients - and trigger a new message to some of them - from the UDP 
> listener.
> Many thanks

  Something like this, perhaps:

    from twisted.internet import protocol, reactor
    from twisted.application import service

    class SomeFactory(protocol.ServerFactory):
        def __init__(self, service):
            self.service = service

        def buildProtocol(self, addr):
            p = protocol.ServerFactory.buildProtocol(self, addr)
            return p

    class SomeDatagramProtocol(protocol.DatagramProtocol):
        def __init__(self, service):
            self.service = service

        def datagramReceived(self, dgram, addr):
            id, msg = extractStuff(dgram)
            self.service.broadcastMessage(id, msg)

    class FoobleService(service.Service):
        def startService(self):
            udpP = SomeDatagramProtocol(self)
            self.udpPort = reactor.listenUDP(..., udpP)
            tcpF = SomeFactory(self)
            self.tcpPort = reactor.listenTCP(..., tcpF)
            self.clients = []

        def stopService(self):
            del self.udpPort, self.tcpPort

        # The interesting bit
        def addClient(self, proto):

        def broadcastMessage(self, id, msg):
            for c in self.clients:
                if c.id == id:

  In other words, construct a system for tracking clients, based on the callbacks Twisted does provide, and then access those clients as desired.  Cleaning up after clients which drop their connection is left as an exercise for the reader.


More information about the Twisted-Python mailing list