Skip to content

Instantly share code, notes, and snippets.

@gmoothart
Created September 18, 2012 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gmoothart/3744225 to your computer and use it in GitHub Desktop.
Save gmoothart/3744225 to your computer and use it in GitHub Desktop.
json-rpc client
"""
A command-line client. Run `twistd -ny jsonrpc_dev.py` first before running this.
"""
# TODO:
# 1) pretty-print json
# 2) take hostname and port as optional parameters
import sys
from twisted.internet import reactor, protocol
from twisted.internet.endpoints import TCP4ClientEndpoint
class EchoClient(protocol.Protocol):
"""Once connected, send a message, then print the result."""
def sendMessage(self, method, params):
rq = '{{"jsonrpc":"2.0","id":"foo123","method":"{}","params":{}}}'.format(method, params)
print "sending request:\n", rq
self.transport.write(rq)
def dataReceived(self, data):
"As soon as any data is received, write it back."
print "Server said:\n", data
class EchoFactory(protocol.ClientFactory):
def buildProtocol(self, addr):
return EchoClient()
def sendAndQuit(p, method, params):
p.sendMessage(method, params)
reactor.callLater(2, p.transport.loseConnection)
reactor.callLater(2, reactor.stop)
# this connects the protocol to a server runing on port 8000
def main():
if (len(sys.argv) < 3):
print """Usage: `python client.py method parameters`
example: `python client.py getEcho '{"foo":"bar"}'`
"""
return
method = sys.argv[1]
params = sys.argv[2]
point = TCP4ClientEndpoint(reactor, "localhost", 7000)
d = point.connect(EchoFactory())
d.addCallback(sendAndQuit, method, params)
reactor.run()
# this only runs if the module was *not* imported
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment