简体   繁体   中英

Can anyone explain this code

Have a confusion , In the following code "gotProtocol" is passed to the callback function.while executing this with the sample server program,it could able to send those string with the method "sendMessage" which we registered in the class greeter . But HOW ?

from twisted.internet import reactor
from twisted.internet.protocol import Factory, Protocol
from twisted.internet.endpoints import TCP4ClientEndpoint

class Greeter(Protocol):
    def sendMessage(self, msg):
        self.transport.write("MESSAGE %s\n" % msg)

class GreeterFactory(Factory):
    def buildProtocol(self, addr):
        return Greeter()

def gotProtocol(p):
    p.sendMessage("Hello")
    reactor.callLater(1, p.sendMessage, "This is sent in a second")
    reactor.callLater(2, p.transport.loseConnection)

point = TCP4ClientEndpoint(reactor, "localhost", 1234)
d = point.connect(GreeterFactory())
d.addCallback(gotProtocol)
reactor.run()

Its asynchronous programming. It can be a little confusing at first. The basic idea is that you define functions and pass them to the library and it will execute them when it needs to.

gotProtocol is a callback function. addCallback is not calling it, the function is being passed as an argument and stored to be called later.

The variable p represents the value that will be passed when twisted calls your standalone function gotProtocol and will give the function context (ie you will have something to operate on).

To show a very simple example of this

import time
# imagine this function is defined in a library
def libraryfunc(cb):
    time.sleep(1)
    cb(1)

# your callback function that will be called later by library
def mycb(i):
    print "the library returned me %d" % i

libraryfunc(mycb)

You pass the library a function and it will pass you something back later by calling that function.

p will be a Greeter instance. As Greeter inherits from Protocol it can be used polymorphically as a Protocol object internally by twisted, but when you receive it you can call the extra method specific to the Greeter class sendMessage as well as the methods inherited from Protocol that will do the networky stuff eg self.transport.write .

As for how and when the Greeter instance is created. You provided a factory class that will return an instance of Greeter so twisted can create the instance when it needs to and return it to you in the callback. The advantage of the factory method is that twisted doesn't need to know the concrete class it is instantiating, as long as the class inherits from Protocol its useable.

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