[Twisted-Python] Twisted Client
Lucas Taylor
ltaylor.volks at gmail.com
Tue Nov 10 16:59:12 MST 2009
On 11/10/09 6:25 AM, morbidux wrote:
> Hi all,
>
> I'm writing a simple client / server application, that uses a small
> protocol to dialog.
>
> I can't find in documentation any exemple that would correspond to what my
> client is supposed to do.
>
> Here is the basics :
>
> every X seconds, call a function that check a file
> if file is different, connect to server
>
> When the client is connected, it immediatly sends data to server, using
> the connectionMade method.
>
> Do I need to use while(1) loop or loopingCall ? What is the best way to
> write a daemon that connect to a server every X seconds ?
>
You could setup a LoopingCall that calls your file checking function.
Your file checking function can then use
twisted.internet.protocol.ClientCreator to send your data.
A simple example:
import os
from twisted.internet import reactor
from twisted.internet.protocol import Protocol, ClientCreator
from twisted.internet.task import LoopingCall
from twisted.python import log
def gotProtocol(p, data):
p.transport.write(data)
p.transport.loseConnection()
def errHandler(reason):
log.err(reason)
def checkFile():
if os.path.exists('sentry.file'):
c = ClientCreator(reactor, Protocol)
c.connectTCP("localhost", 1234).addCallback(gotProtocol, 'some
data').addErrback(errHandler)
lp = LoopingCall(checkFile)
lp.start(5, now=True)
reactor.run()
--
If you want to maintain state between protocol instances, then create a
ClientFactory. You could look at how ReconnectingClientFactory is
implemented for ideas.
The Writing Clients howto should help:
http://twistedmatrix.com/projects/core/documentation/howto/clients.html
Lucas Taylor
More information about the Twisted-Python
mailing list