python rpc

2021-01-18 17:20

阅读:794

标签: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


评论


亲,登录后才可以留言!