Python Network Programming RPC JSON Server

Python Network Programming RPC JSON Server

JSON, or JavaScript Object Notation, is a lightweight data-interchange format. It’s easy for humans to read and write, and for machines to parse and generate. JSON-based RPC calls can send data in a more compact and efficient manner than standard XML-based RPC calls. The Python module jsonrpclib can create a simple JSON-based server and client.

Example

In the following example, we create a simple JSON server and a function within it. This function breaks a large list into smaller lists, noting the length of the arguments and the arguments themselves.

# server program
from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer

def findlen(*args):

res = []
for arg in args:
try:
lenval = len(arg)
except TypeError:
lenval = None
res.append((lenval, arg))
return res

def main():
server = SimpleJSONRPCServer(('localhost', 1006))
server.register_function(findlen)
print("Start server")
server.serve_forever()
if __name__ == '__main__':
main()

# Call by client
from jsonrpclib import Server
def main():
conn = Server('http://localhost:1006')
print(conn.findlen(('a', 'x', 'd', 'z'), 11, {'Mt. Abu': 1602, 'Mt. Nanda': 3001, 'Mt. Kirubu': 102, 'Mt. Nish': 5710}))
if __name__ == '__main__':
main()

When we run the above program, we get the following output −

[[4, [u'a', u'x', u'd', u'z']], [None, 11], [4, {u'Mt. Abu': 1602, u'Mt. Kirubu': 102, u'Mt. Nanda': 3001, u'Mt. Nish': 5710}]]

Leave a Reply

Your email address will not be published. Required fields are marked *