[Twisted-Python] TCP client that can connect to a server at periodic intervals

glyph at divmod.com glyph at divmod.com
Mon Mar 5 14:55:43 MST 2007


On 05:58 pm, bradley.s.gaspard at saic.com wrote:
>
>I am trying to write a TCP client that at regular intervals connects to 
>a server makes a request and then closes the connection.

Your code has a fatal problem.  Nowhere are you actually creating a 
client connection, you're just creating protocol objects and not hooking 
them up to anything!  I've whipped up a quick periodic ping/pong 
client/server pair for you here, which should provide a useful starting 
point for you.

The key thing is the call to the ClientCreator's 'connectTCP' method, 
which actually hooks up an instantiated PingSender to a socket.

-------- cut

from twisted.internet.protocol import Protocol, ClientCreator, Factory
from twisted.internet.task import LoopingCall
from twisted.internet import reactor

class PingResponder(Protocol):
    buf = ''
    def dataReceived(self, data):
        self.buf += data
        if self.buf == 'PING':
            print 'PONGED!'
            self.transport.write('PONG')
            self.transport.loseConnection()

class PingSender(Protocol):
    buf = ''
    def connectionMade(self):
        self.transport.write("PING")
    def dataReceived(self, data):
        self.buf += data
    def connectionLost(self, reason):
        print "PONGED WITH: " +self.buf

def client():
    cc = ClientCreator(reactor, PingSender)
    def dontDelay():
        cc.connectTCP('localhost', 4321)
    lc = LoopingCall(dontDelay)
    lc.start(0.5)


def server():
    pf = Factory()
    pf.protocol = PingResponder
    svr = reactor.listenTCP(4321, pf)

import sys
if sys.argv[1] == 'client':
    client()
else:
    server()

reactor.run()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: </pipermail/twisted-python/attachments/20070305/7bda4d9f/attachment.html>


More information about the Twisted-Python mailing list