Python implements RPC - simple use of xmlrpc library

1. Introduction to RPC

RPC (Remote Procedure Call) remote procedure call, which is a service request from a remote computer program through the network. RPC is a design to solve the call problem between different services. A complete RPC implementation generally includes two transport protocols and serialization protocols.

RPC adopts the client/server model. A requesting program is a client, and a service-providing program is a server. First, the client calling process sends a request message to the server, and then waits for a response message. On the server side, the process stays asleep until the requested information arrives. When a request message arrives, the server obtains the process parameters, then executes the corresponding service method and returns the result to the client, and then continues to wait for the next request message until the server process is closed.

In Python3, the xmlrpc library is used to implement RPC, which is divided into xmlrpc.server and xmlrpc.client.

2. Examples of using the xmlrpc library

1. rpc server implementation

rpc_server.py

from xmlrpc.server import SimpleXMLRPCServer


# 1.定义能被客户端调用的类
class MethodSet(object):
    @staticmethod
    def say_hello():
        print("MethodSet的方法正在被调用...")
        str1 = "hello rpc!"
        return str1


# 2.定义能被客户端调用的函数
def say_hi():
    print("say_hi 函数正在被调用...")
    str2 = "hi rpc~"
    return str2


# 3.注册一个函数或者类来响应XML-RPC请求,并启动XML-RPC服务器
def setup_socket_service(server_ip="localhost", server_port=6666):
    try:
        server = SimpleXMLRPCServer((server_ip, server_port))  # 初始化XML-RPC服务
        print('Server {} Listening on port {} ...'.format(server_ip, server_port))
        server.register_instance(MethodSet())  # 注册一个类
        server.register_function(say_hi)  # 注册一个函数
        server.serve_forever()  # 启动服务器并永久运行
    except Exception as ex:
        raise Exception('Setup socket server error:\n{}'.format(ex))


if __name__ == '__main__':
    setup_socket_service()

Start the server (the program should be running all the time, do not close it): python rpc_server.py
After starting the result:

min@LAPTOP-E6G8RE06 MINGW64 /e/study/mat
$ python rpc_server.py
Server localhost Listening on port 6666 ...

2. Client implementation

rpc_client.py

from xmlrpc.client import ServerProxy


def setup_socket_client(ip_address, port=6666):
    proxy = ServerProxy('http://%s:%s/' % (ip_address, port), allow_none=True)
    print('Connect to {}:{} successful ...'.format(ip_address, port))

    ret1 = proxy.say_hello()   # 调用
    print('Received the ret1 is {}'.format(ret1))

    ret2 = proxy.say_hi()  # 调用
    print('Received the ret2 is {}'.format(ret2))


if __name__ == '__main__':
    setup_socket_client(ip_address='localhost')

Start the client and initiate a request. python rpc_client.py
Call result (client):

min@LAPTOP-E6G8RE06 MINGW64 /e/study/mat
$ python rpc_client.py
Connect to localhost:6666 successful ...
Received the ret1 is hello rpc!
Received the ret2 is hi rpc~

Call result (server):

min@LAPTOP-E6G8RE06 MINGW64 /e/study/mat
$ python rpc_server.py
Server localhost Listening on port 6666 ...
MethodSet的方法正在被调用...
127.0.0.1 - - [19/Jun/2021 19:58:11] "POST / HTTP/1.1" 200 -
say_hi 函数正在被调用...
127.0.0.1 - - [19/Jun/2021 19:58:13] "POST / HTTP/1.1" 200 -

Guess you like

Origin blog.csdn.net/weixin_45455015/article/details/118058401