Here is a simple example showing how to correctly use the UDP multicast functionality of twisted.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | # Simple UDP Multicast Server example
# Kyle Robertson
# A Few Screws Loose, LLC
# http://www.afslgames.com
# ra1n@gmx.net
# MulticastServer.py
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
from twisted.application.internet import MulticastServer
class MulticastServerUDP(DatagramProtocol):
def startProtocol(self):
print 'Started Listening'
# Join a specific multicast group, which is the IP we will respond to
self.transport.joinGroup('224.0.0.1')
def datagramReceived(self, datagram, address):
# The uniqueID check is to ensure we only service requests from ourselves
if datagram == 'UniqueID':
print "Server Received:" + repr(datagram)
self.transport.write("data", address)
# Note that the join function is picky about having a unique object
# on which to call join. To avoid using startProtocol, the following is
# sufficient:
#reactor.listenMulticast(8005, MulticastServerUDP()).join('224.0.0.1')
# Listen for multicast on 224.0.0.1:8005
reactor.listenMulticast(8005, MulticastServerUDP())
reactor.run()
#############################################################################
# Simple UDP Multicast Client example
# Kyle Robertson
# A Few Screws Loose, LLC
# http://www.afslgames.com
# ra1n@gmx.net
# MulticastClient.py
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
from twisted.application.internet import MulticastServer
class MulticastClientUDP(DatagramProtocol):
def datagramReceived(self, datagram, address):
print "Received:" + repr(datagram)
# Send multicast on 224.0.0.1:8005, on our dynamically allocated port
reactor.listenUDP(0, MulticastClientUDP()).write('UniqueID', ('224.0.0.1', 8005))
reactor.run()
|
I've seen alot of discussion about how to correctly do this, so here is an example to give some insight into the basics.
Tags: network