| 1 |
#!/usr/bin/env python |
| 2 |
|
| 3 |
# Copyright (c) Twisted Matrix Laboratories. |
| 4 |
# See LICENSE for details. |
| 5 |
|
| 6 |
""" |
| 7 |
An example demonstrating how to send and receive UDP broadcast messages. |
| 8 |
|
| 9 |
Every second, this application will send out a PING message with a unique ID. |
| 10 |
It will respond to all PING messages with a PONG (including ones sent by |
| 11 |
itself). You can tell how many copies of this script are running on the local |
| 12 |
network by the number of "RECV PONG". |
| 13 |
|
| 14 |
Run using twistd: |
| 15 |
|
| 16 |
$ twistd -ny udpbroadcast.py |
| 17 |
""" |
| 18 |
|
| 19 |
from uuid import uuid4 |
| 20 |
|
| 21 |
from twisted.application import internet, service |
| 22 |
from twisted.internet.protocol import DatagramProtocol |
| 23 |
from twisted.python import log |
| 24 |
|
| 25 |
|
| 26 |
class PingPongProtocol(DatagramProtocol): |
| 27 |
noisy = False |
| 28 |
|
| 29 |
def __init__(self, controller, port): |
| 30 |
self.port = port |
| 31 |
|
| 32 |
def startProtocol(self): |
| 33 |
self.transport.setBroadcastAllowed(True) |
| 34 |
|
| 35 |
def sendPing(self): |
| 36 |
pingMsg = f"PING {uuid4().hex}" |
| 37 |
pingMsg = pingMsg.encode("ascii") |
| 38 |
self.transport.write(pingMsg, ("<broadcast>", self.port)) |
| 39 |
log.msg(b"SEND " + pingMsg) |
| 40 |
|
| 41 |
def datagramReceived(self, datagram, addr): |
| 42 |
if datagram[:4] == b"PING": |
| 43 |
uuid = datagram[5:] |
| 44 |
pongMsg = f"PONG {uuid}" |
| 45 |
pongMsg = pongMsg.encode("ascii") |
| 46 |
self.transport.write(pongMsg, ("<broadcast>", self.port)) |
| 47 |
log.msg(b"RECV " + datagram) |
| 48 |
elif datagram[:4] == b"PONG": |
| 49 |
log.msg(b"RECV " + datagram) |
| 50 |
|
| 51 |
|
| 52 |
class Broadcaster: |
| 53 |
def ping(self, proto): |
| 54 |
proto.sendPing() |
| 55 |
|
| 56 |
def makeService(self): |
| 57 |
application = service.Application("Broadcaster") |
| 58 |
|
| 59 |
root = service.MultiService() |
| 60 |
root.setServiceParent(application) |
| 61 |
|
| 62 |
proto = PingPongProtocol(controller=self, port=8555) |
| 63 |
root.addService(internet.UDPServer(8555, proto)) |
| 64 |
root.addService(internet.TimerService(1, self.ping, proto)) |
| 65 |
|
| 66 |
return application |
| 67 |
|
| 68 |
|
| 69 |
application = Broadcaster().makeService() |