Skip to content Skip to main navigation Skip to footer

Python: 使用Java调用Python服务器RPC

#先上一个整体的Python代码,它可以作为Python建立RPC服务器或客户端的通用库

#test_rpc.py
#coding=utf-8
from SimpleXMLRPCServer import SimpleXMLRPCServer
from 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

原文:http://my.oschina.net/crooner/blog/417011

0 Comments

There are no comments yet

Leave a comment

Your email address will not be published.