[Message Prev][Message
Next][Thread Prev][Thread Next][Message
Index][Thread Index]
Re: Python
- Subject: Re: Python
- From: "mark_harrison_uk2" <mph@xxxxxxxxxxxxxxx>
- Date: Thu, 10 Feb 2005 16:25:09 -0000
--- In xAP_developer@xxxxxxx, "mark_harrison_uk2"
<mph@a...>
wrote:
... and today, a hub-aware, heart-beat pumping, version of the
"PythonListener" that certainly works with Stuart's .NET hub, and
picks up messages from Patrick's embedded Rio application.
Source code below. It seems very, very, little for quite a lot of
work, but I was learning the language from scratch, and I've
re-written it all about a dozen times today ending up with this, which
I think is the most elegant.
Mark
--------------------------------------------
# import some standard Python classes
import time, thread, SocketServer, socket
# we need to start by defining the various functions
# xapHandler is what is called when a UDP packet is received
# because of the way that the inbuilt SocketServer class works,
# it's implemented as a class with a default handler
class xapHandler(SocketServer.DatagramRequestHandler):
def handle(self):
print "Incoming message from ", self.client_address[0]
message=self.rfile.read()
header=message[message.find('{')+2:message.find('}')]
print header
# xapheartbeat builds a heartbeat message (once it knows its port)
# and sends it repeatedly every sleeptime seconds
def xapheartbeat(port,sleeptime,*args):
print "Starting heartbeats"
heartbeatmessage="xap-hbeat\n{\nv=12\nhop=1\nuid=FF001100\n"
heartbeatmessage+="class=xap-hbeat.alive\nsource=scentium.python.test."
heartbeatmessage +=socket.getfqdn(socket.gethostname())
heartbeatmessage+="\ninterval=60\nport="
heartbeatmessage +=str(port)
heartbeatmessage += "\n}"
heartbeat=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
heartbeat.connect(('255.255.255.255',3639))
while 1:
heartbeat.send(heartbeatmessage)
time.sleep(sleeptime)
# xaplistener tries to open a listener socket on 3639 on the primary
IP address
# if that fails, it adds one to the listener port and tries again
# in case you're wondering about the shrubbery, it's because threads
have to be
# called with two arguments, a function and a tuple of parameters, and
I've
# not sussed how to make a tuple with only one argument
def xaplistener(baseport,shrubbery):
try:
print "starting listener on", baseport
serv = SocketServer.UDPServer(('',baseport), xapHandler)
thread.start_new_thread(xapheartbeat,(baseport,60))
serv.serve_forever()
except:
print "sorry - ", baseport, "in use"
xaplistener(baseport+1, 0)
# now we get the actual routine
if __name__=="__main__":
print 'Copyright 2005 Mark Harrison ltd.'
print 'xap listener 1.1 - heartbeating, hub aware'
xaplistener(3639, 0)
xAP_Development Main Index |
xAP_Development Thread Index |
xAP_Development Home |
Archives Home
|