zfou
zfou

Reputation: 921

Calling a client's remote method in Twisted perspective broker

I am using twisted's Perspective Broker to talk between the client and the server. The client requests from the server a remote method 'remote_ftp_listen'. This causes the PB server to initiate a FTP connection and wait till a file matching some pattern is found in a directory, then the PB server must inform the client of that event (found a file in the desired ftp directory).

How to achieve this reverse call (PB Server > PB client) ? something like telling the server that it has to callback a method on the client side ... if it's not possible through PB, then what would you advise to do to realize it ?

Upvotes: 2

Views: 825

Answers (1)

Jean-Paul Calderone
Jean-Paul Calderone

Reputation: 48335

When the client does this:

clientDeferred = server.callRemote("ftp_listen", arguments)

And the server does this:

def remote_ftp_listen(self, arguments):
   # ... some stuff with FTP ...
   serverDeferred = ftpConnection.findSomeFile(arguments)
   return serverDeferred

where findSomeFile returns an instance of Deferred, then the PB server will send back a response to the client after serverDeferred fires, and clientDeferred will fire after the client receives that response from the server.

You can also return multiple results this way, if you're happy for them to all be returned at once (which will happen when the last one is found). Just adjust the server:

from twisted.internet.defer import gatherResults

def remote_ftp_listen(self, arguments):
   # ... some stuff with FTP ...
   serverDeferred = gatherResults([ftpConnection.findSomeFile(a) for a in arguments])
   return serverDeferred

The Deferred returned by gatherResults will fire with a list holding the results of all of the Deferred objects in the list passed to it.

If you need to send results to the client as soon as they are discovered, rather than bundling them all up into a single result list, then you need to do something different. Have the client pass a Referenceable to the server and have the server call remote methods on that object. You can read more about this approach on the Twisted website in the PB documentation. http://twistedmatrix.com/documents/current/core/howto/pb-usage.html in particular goes into this topic. The document focuses on passing Referenceable objects from server to client, but the reverse works exactly the same way. So if you have a Referenceable on your client that you pass to the ftp_listen remote method on the server, then the server will be able to turn around and use callRemote to call methods on the client object.

Upvotes: 2

Related Questions