服務端的實現:
import SimpleXMLRPCServer,osrunning=Truefuns=['add','minus','exit','getCurrentList','linuxCmd']
#new code解決rpc調用速度慢#每次返回的時候BaseHTTPRequestHandler 都會調用log_message 方法記錄一些日誌資訊,而log_message方法需要知道請求的host 。# 問題就出在這裡,當沒有host的時候程式會調用_socket 的gethostname()方法,而伺服器上並沒有配置驛應的host。import BaseHTTPServerdef not_insane_address_string(self): host, port = self.client_address[:2] return '%s (no getfqdn)' % host #used to call: socket.getfqdn(host)BaseHTTPServer.BaseHTTPRequestHandler.address_string =\not_insane_address_string
#end new codeclass ExposeFuns(object): def add(self,a,b): return a+b def minus(self,a,b): return a-b def exit(self): global running running=False return 'exit!' def getCurrentList(self): return os.getcwd() def listDir(self,dir): return os.listdir(dir) def linuxCmd(self,dir): return os.popen(dir).read() def useage(self): return funs;server= SimpleXMLRPCServer. SimpleXMLRPCServer(('localhost',8000))server.register_instance(ExposeFuns())#server.register_function(add)while running: server.handle_request()
用戶端的實現:
import xmlrpclibserver=xmlrpclib.Server('http://127.0.0.1:8000')print server.add(5,88)print server.minus(server.add(5,88),5)print server.finis()