Re: udp broadcast example, please

From: Jp Calderone (exarkun_at_intarweb.us)
Date: 12/17/03


Date: Wed, 17 Dec 2003 10:27:49 -0500
To: Python-list@python.org

On Wed, Dec 17, 2003 at 01:22:25PM +0200, Torsten Rueger wrote:
> Moi,
>
> sorry, but I've searched and searched to find exact information on how
> to do a simple udp broadcast client/server, but can find it:
>
> I want to have a thread pinging (very small message) and possibly the
> same thread receiving maybe with a 1 second timeout. And the same code
> should be able to run as multiple instances on the same machine.
>
> Could someone with experience please post the 10 lines to make this
> happen. Please no general comments or things that "should" work. I've
> tried for hours with various socket options and addresses, so I would
> very much appreciate working code.
>

  No threads, but maybe it's good enough anyway:

    import sys
    from socket import SOL_SOCKET, SO_BROADCAST

    from twisted.internet import reactor
    from twisted.internet import protocol
    from twisted.internet import task
    from twisted.python import log

    log.startLogging(sys.stdout)

    port = 7154

    class BroadcastingDatagramProtocol(protocol.DatagramProtocol):

        port = port

        def startProtocol(self):
            self.transport.socket.setsockopt(SOL_SOCKET, SO_BROADCAST, True)
            self.call = task.LoopingCall(self.tick)
            self.dcall = self.call.start(1.0)

        def stopProtocol(self):
            self.call.stop()

        def tick(self):
            self.transport.write(self.getPacket(), ("<broadcast>", self.port))

        def getPacket(self):
            return "Some bytes for you"

        def datagramReceived(self, data, addr):
            print "Received", repr(data)

    reactor.listenUDP(port, BroadcastingDatagramProtocol())
    reactor.run()

  Jp