Sunday, May 07, 2006

Twisted JSON-RPC TCP Proxy and Server

twisted :: python :: internet

Yesterday I finished the Twisted JSON-RPC server and proxy for TCP. I
decided to go with the
Netstring protocol
for its simplicity and the security of declaring and limiting string

Usage is very simple and almost identical to the HTTP-based Twisted
JSON-RPC usage. Here is some server code:

from twisted.application import service, internet

from adytum.twisted import jsonrpc

class Example(jsonrpc.JSONRPC):
"""An example object to be published."""

def jsonrpc_echo(self, x):
"""Return all passed args."""
return x

factory = jsonrpc.RPCFactory(Example)
application = service.Application("Example JSON-RPC Server")
jsonrpcServer = internet.TCPServer(7080, factory)

And for the client:

from twisted.internet import reactor
from twisted.internet import defer

from adytum.twisted.jsonrpc import Proxy

def printValue(value):
print "Result: %s" % str(value)

def printError(error):
print 'error', error

def shutDown(data):
print "Shutting down reactor..."

print "Making remote calls..."
proxy = Proxy('', 7080)

d = proxy.callRemote('echo', 'hey!')
d.addCallbacks(printValue, printError)

For a slightly more complex example (with subhandlers and
introspection) see:
the wiki.

Next on the list? For a truly secure solution, I am exploring the use
of the
Perspective Broker

Now playing:
Yoko Kanno & The Seatbelts - Forever Broke

No comments:

Post a Comment