[Twisted-Python] Polling from Twisted
Lucas Taylor
ltaylor.volks at gmail.com
Tue Apr 28 01:48:37 MDT 2009
On 4/27/09 5:06 PM, Juanjo Conti wrote:
> Hi, this is my first mail to the list.
>
> I am writing a server using Twisted, extending LineOnlyReceiver. In it I
> maintain a list of clients connected.
>
> I'd like to poll every client for certain status information every 30
> seconds. Which is the correct approach to implement this?
>
A simple option is to setup a task.LoopingCall in your factory to
iterate over the list of clients every 30 seconds and issue your status
request. I don't know if it is correct for your application, but this
should illustrate the basic idea:
from twisted.internet import reactor, task
class StatusPollingReceiver(LineOnlyReceiver):
def connectionMade(self):
self.factory.clients.append(self)
def lineReceived(self, line):
print('Rx: %s' % line)
def connectionLost(self, reason):
self.factory.clients.remove(self)
class StatusPollingFactory(Factory):
def __init__(self):
self.clients = []
# send a status request to each client every 30 seconds
self.statusloop = task.LoopingCall(self.requestStatus)
self.statusloop.start(30.0)
def requestStatus(self):
for client in self.clients:
client.transport.write('stat\r\n')
def stopFactory(self):
self.statusloop.stop()
def buildProtocol(self, addr):
p = StatusPollingReceiver()
p.factory = self
return p
see:
http://twistedmatrix.com/documents/current/api/twisted.internet.task.LoopingCall.html
More information about the Twisted-Python
mailing list