码迷,mamicode.com
首页 > 编程语言 > 详细

python rpc

时间:2020-05-18 20:44:29      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:proxy   register   soc   res   http   com   rev   for   eve   

参考:https://www.cnblogs.com/ExMan/p/10408353.html

用python的rpc库SimpleXMLRPCServer 做测试,创建rpc server,然后注册一些函数,供应别的客户端去调用

rpc_server.py:

from xmlrpc.server import SimpleXMLRPCServer


def add(x, y):
	return x + y


def subtract(x, y):
	return x - y


def multiply(x, y):
	return x * y


def divide(x, y):
	return x // y


server = SimpleXMLRPCServer((‘127.0.0.1‘, 8080))
print(‘listening on port 8080‘)

server.register_multicall_functions()
server.register_function(add, ‘add‘)
server.register_function(subtract, ‘subtract‘)
server.register_function(multiply, ‘multiply‘)
server.register_function(divide, ‘divide‘)

server.serve_forever()

rpc_client.py:

from xmlrpc.client import ServerProxy, MultiCall

proxy = ServerProxy((‘http://127.0.0.1:8080‘))

multicall = MultiCall(proxy)

multicall.add(5, 3)
multicall.subtract(5, 3)
multicall.multiply(5, 3)
multicall.divide(5, 3)
result = multicall()

print("5+3=%d, 5-3=%d, 5*3=%d, 5//3=%d" % tuple(result))

RPC本来是单任务的,如果任务相对频繁,可以设置成多线程的默认,你不用在调用threading模块什么的,直接引用:

rpc_thread_server.py:

from xmlrpc.server import SimpleXMLRPCServer
from socketserver import ThreadingMixIn


class ThreadXMLRPCServer(ThreadingMixIn, SimpleXMLRPCServer):
	pass


def add(x, y):
	return x + y


def subtract(x, y):
	return x - y


def multiply(x, y):
	return x * y


def divide(x, y):
	return x // y


server = ThreadXMLRPCServer((‘127.0.0.1‘, 8080), allow_none=True)  # 初始化
print(‘listening on port 8080‘)

server.register_multicall_functions()
server.register_function(add, ‘add‘)
server.register_function(subtract, ‘subtract‘)
server.register_function(multiply, ‘multiply‘)
server.register_function(divide, ‘divide‘)

server.serve_forever()

rpc_client.py不变。

python rpc

标签:proxy   register   soc   res   http   com   rev   for   eve   

原文地址:https://www.cnblogs.com/lovebkj/p/12912074.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!