简体   繁体   中英

Twisted Deferred with periodical calls

My Problem looks like this: I have a Twisted Server, which sends values every 2 seconds over TCP with callLater. And I have a twisted client, which recieves the values and should handle the recieving value with a deferred.

My Server looks like this:

from twisted.internet.protocol import ServerFactory
from twisted.protocols.basic import NetstringReceiver
from random import randint

class ServerProtocol(NetstringReceiver):
    def __init__(self, factory):
        self.factory = factory
        self.sendObject = None

    def connectionMade(self):        
        self.sendValue()

    def connectionLost(self, reason):
        sendObject, self.sendObject = self.sendObject, None
        sendObject.cancel()

    def sendValue(self):
        data = randint(2,20)
        self.sendString(str(data))
        print('send: {0}'.format(data))

        from twisted.internet import reactor
        self.sendObject = reactor.callLater(2, self.sendValue)

class MyServerFactory(ServerFactory):

    def __init__(self):
        self.protsa = []

    def buildProtocol(self, addr):
        return ServerProtocol(self)

    def setCallback(self, callback):
        self.callback = callback    

def serverMain():

    factory = MyServerFactory()
#    factory.setCallback(generateVal)

    from twisted.internet import reactor

    port = reactor.listenTCP(2345, factory, interface='127.0.0.1')     
    print 'Serving on %s.' % (port.getHost())

    reactor.run()


if __name__ == '__main__':
    serverMain()

My Client looks like this:

from twisted.internet.protocol import ClientFactory
from twisted.protocols.basic import NetstringReceiver
from twisted.internet import defer


class ClientProtocol(NetstringReceiver):

    def stringReceived(self, string):
        print("recieved")
        self.factory.printValue(string)

    def connectionMade(self):
        print("Made Connection")

    def connetionLost(self):
        print("Connection Lost")

class MyClientFactory(ClientFactory):

    protocol = ClientProtocol

    def __init__(self, deferred):
        self.deferred = deferred

    def clientConnectionFailed(self, connector, reason):
        if self.deferred is not None:
            d, self.deferred = self.deferred, None
            d.errback(reason)

    def printValue(self, value):
        if self.deferred is not None:
            d, self.deferred = self.deferred, None
            d.callback(value)


def OutputValue(host, port):
    d = defer.Deferred()
    from twisted.internet import reactor
    factory = MyClientFactory(d)
    reactor.connectTCP(host, port, factory)
    return d

def clientMain():

    def writeError(err):
        print("Deferred Error!\n")
        print("Error: {0}".format(err.__str__))

    def writeValue(value):
        print("Value revieved: {0}".format(value))

    from twisted.internet import reactor

    d = OutputValue('127.0.0.1', 2345)
    d.addCallbacks(writeValue, writeError)

    reactor.run()

if __name__ == '__main__':
    clientMain()

Output:

Made Connection
recieved
Value revieved: 11
recieved
recieved
recieved

For the first time everything works fine. After connection the server sends a value which the client recieves. The client handels the with a deferred as wished. The second value are not handled by the deferred. I also expected that because the deferred are only fired once. Now I would like to have a possibility to handle every recieved value by a deferred, so I can also do error handling.

I had a look at this:

Twisted: deferred that fires repeatedly

Re-using deferred objects in Twisted

but I cannot get hold of a solution for my problem. This can't be so unusual. Or do I have to disconnect and connect every time?

A Deferred is an object which represents the result of a specific request that you are making. But since a request can only have one associated response, in the same way that a function can only return once, a Deferred can only be fired once.

You already have a function - printValue - which is run when a value is received and should be printed. Why not just print the value in that function right away, rather than going looking for a Deferred which your caller set up?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM