Python Network Programming 简明教程

Python - RPC JSON Server

JSON 或 JavaScript 对象表示法是一种轻量级数据交换格式。它便于人类阅读和书写。它易于机器解析和生成。基于 JSON 进行的 RPC 调用能够以比基于 XML 的正常 RPC 调用更加紧凑和有效的方式发送数据。python 模块 jsonrpclib 能够创建基于 JSON 的简单服务器和客户端。

JSON or JavaScript Object Notation is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. The RPC call made based on JSON is able to send data in a much compact and efficient manner than the normal XML based RPC call. The python module jsonrpclib is able to create a simple JSON based server and client.

Example

在下面的示例中,我们创建一个简单的 JSON 服务器,并在其中创建一个函数。此函数将一个较大的列表分解为较小的列表,指出参数的长度和参数本身。

In the below example we create a simple JSON server and create a function in it. This function breaks a bigger list into smaller lists mentioning the length of the argument as well as the argument itself.

# 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}]]