[Twisted-Python] How to send a UDP datagram

Jp Calderone exarkun at divmod.com
Sat Sep 24 12:24:14 EDT 2005

On Sat, 24 Sep 2005 11:33:50 -0400, Drake Smith <drakesmith at adelphia.net> wrote:
>Can somebody please show me the Twisted way to send a simple UDP datagram? 
> From the examples, I see how to transport.write in response to receiving a 
>datagram or in response to establishing a UDP "connection". But in my 
>application, I'd like to send datagrams blindly, say, to initiate a 
>heartbeat message or to stream audio samples without acknowledgement via an 
>unconnected UDP socket. I'd also like to do this from a function that is not 
>wrapped inside a Twisted protocol class as such, unless that is contrary to 
>the Twisted approach.
>I am using Twisted version 2.0.1/Python 2.4 on a Linux box. Thank you.

When a DatagramProtocol is hooked up to a transport, its startProtocol method is invoked.  Here's how I'd write a heartbeat thingy:

  from twisted.internet import protocol, reactor, task

  class Heartbeat(protocol.DatagramProtocol):
      def sendHeartbeat(self):

      def startProtocol(self):
          self._call = task.LoopingCall(self.sendHeartbeat)
          self._loop = self._call.start(15)

      def stopProtocol(self):

  reactor.listenUDP(0, Heartbeat())

There's nothing particularly unique to Twisted if you want to turn this inside out and have some other code controlling the loop, but here's an example of that just for completeness:

  from twisted.internet import protocol, reactor, task

  class Heartbeat(protocol.DatagramProtocol):
      def __init__(self, onStart):
          self.onStart = onStart

      def startProtocol(self):

      def sendHeartbeat(self):

  class HeartbeatSenderGuy(object):
      def start(self):
          d = defer.Deferred()
          self._port = reactor.listenUDP(0, Heartbeat(d))

      def _listening(self, proto):
          self._proto = proto
          self._call = task.LoopingCall(self._proto.sendHeartbeat)

      def stop(self):

  hb = HeartbeatSenderGuy()

Hope this helps,


More information about the Twisted-Python mailing list