標籤:
#先上一個整體的Python代碼,它可以作為Python建立RPC伺服器或用戶端的通用庫
#test_rpc.py#coding=utf-8from SimpleXMLRPCServer import SimpleXMLRPCServerfrom SocketServer import ThreadingMixIn from xmlrpclib import ServerProxy import thread class ThreadXMLRPCServer(ThreadingMixIn, SimpleXMLRPCServer): pass class RPCServer(): def __init__(self, ip=‘127.0.0.1‘, port=‘8000‘): self.ip = ip self.port = int(port) self.svr = None def start(self, func_lst): thread.start_new_thread(self.service, (func_lst, 0,)) def resume_service(self, v1, v2): self.svr.serve_forever(poll_interval=0.001) def service(self, func_lst, v1): self.svr = ThreadXMLRPCServer((self.ip, self.port), allow_none=True) for func in func_lst: self.svr.register_function(func) self.svr.serve_forever(poll_interval=0.001) def activate(self): thread.start_new_thread(self.resume_service, (0, 0,)) def shutdown(self): try: self.svr.shutdown() except Exception, e: print ‘rpc_server shutdown:‘, str(e) class RPCClient(): def __init__(self, ip=‘127.0.0.1‘, port=‘8000‘): self.svr = ServerProxy(‘http://‘+ip+‘:‘+port+‘/‘, allow_none=True, use_datetime=True) def get_svr(self): return self.svr def get_hello(): return ‘hello!‘ if __name__ == "__main__": r = RPCServer(‘0.0.0.0‘, ‘8061‘) r.service([get_hello], 0) #這裡僅僅載入get_hello函數
#啟動test_rpc.py待用
python test_rpc.py
#下面開始Java,首先下載jar包 ,在 https://archive.apache.org/dist/ws/xmlrpc/binaries/ 找到 apache-xmlrpc-3.1.3-bin.tar.gz 。
#apache-xmlrpc-3.1.3-bin.tar.gz包的API文檔 http://ws.apache.org/xmlrpc/apidocs/index.html
#如果使用Eclipse,通過 “右鍵項目根目錄->properties->Java Build Path->Libraries->add External JARs" 匯入jar包
commons-logging-1.1.jar
xmlrpc-client-3.1.3.jar
xmlrpc-server-3.1.3.jar
ws-commons-util-1.0.2.jar
xmlrpc-common-3.1.3.jar
import java.net.URL;import java.net.MalformedURLException;import org.apache.xmlrpc.XmlRpcException;import org.apache.xmlrpc.client.XmlRpcClient;import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;import org.apache.xmlrpc.client.XmlRpcHttpTransportException;public class Test { public static void main(String[] args) throws MalformedURLException, XmlRpcHttpTransportException { XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl(); config.setServerURL(new URL("http://127.0.0.1:8061/RPC2")); XmlRpcClient client = new XmlRpcClient(); client.setConfig(config); // 根據不同的python函數形式,構造參數 // 兩個整形參數 //Object[] params = new Object[] {new Integer(1), new Integer(2)}; // 單個字串參數 //Object[] params = new Object[] {new String("HELLO")}; // 無參數 Object[] params = null; try { // 返回的結果是字串類型,強制轉換res為String類型 String res = (String) client.execute("get_hello", params); System.out.println(res); } catch (XmlRpcException e11) { e11.printStackTrace(); } }}
參考:
http://blog.sina.com.cn/s/blog_6de3aa8a0101jmru.html
使用Java調用Python伺服器RPC