服务端代码
#coding=utf-8
__author__ = 'nate'
import string
from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
from datetime import datetime
class Api:
def __init__(self):
self.string = string
def test(self):
return 'this is test at {now}'.format(now=datetime.now())
def add(a, b):
return a + b
if __name__ == '__main__':
try:
port = 8080
server = SimpleJSONRPCServer(('127.0.0.1', port))
server.register_function(add)
server.register_instance(Api(), allow_dotted_names=True)
print 'listening on port %d' % port
server.serve_forever()
except KeyboardInterrupt:
print 'Exit'
客户端代码
#coding=utf-8
__author__ = 'nate'
import jsonrpclib
from jsonrpclib.jsonrpc import ProtocolError
if __name__ == '__main__':
try:
server = jsonrpclib.Server('http://localhost:8080')
# test function
print server.add(5, 6)
print jsonrpclib.history.request
print jsonrpclib.history.response
# test instance
print server.test()
print server.string.join([str(i) for i in xrange(1, 10)], '*')
# multiple call
multi = jsonrpclib.MultiCall(server)
multi.add(7, 8)
multi.test()
multi.string.join([str(i) for i in xrange(10, 20)], '#')
results = multi()
for result in results:
print result
except ProtocolError, error:
print 'error : {err}'.format(err=error)