rpc协议学习

转载:https://blog.51cto.com/u_15303040/3173452

转载:https://codeantenna.com/a/sLLVnFrrEF

 

 客户端(client):服务调用方

客户端存根(client stub):存放服务端地址信息,将客户端的请求参数打包成网络消息格式,再通过网络传输发送给服务端,比如python中xmlrpc.client中的ServerProxy

 

服务端(server):服务真正的提供者

服务端存根(server stub):接收客户端发过来的消息并进行解析,然后调用本地的服务进行处理,比如xmlrpc.server的SimpleXMLRPCServer

网络(network service):网络传输,tcp或者http

 

eg:通过xmlrpc来实现一个简单的rpc例子

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()

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')

运行结果:

客户端

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~

服务端:

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 -

 

posted on 2023-01-16 17:05  该用户很懒  阅读(29)  评论(0编辑  收藏  举报