Python3 xmlrpc library using simple realization RPC functions

A, RPC Introduction

1. RPC

RPC (Remote Procedure Call) i.e., remote procedure call, which is a service request from a remote computer through a network, without having to understand the underlying network protocol technology. RPC may carry information for the data communication between the communication program. In the OSI model, network communications, across the RPC transport layer and application layer, is a common method of communication in a distributed system.

RPC uses the client / server model. Requestor is a client, while the service-providing program is the server. First, the client calls the process sends a request message to the server, and then waits for a reply message. On the server side, maintain sleep until the process reaches the requested information. When a request message arrives, the server to get the process parameters, and then executes the corresponding service method and return the results to the client, and then continues to wait for a next request for information until you close the server-side process so far.

2. xmlrpc library

In Python2 need to use server-side SimpleXMLRPCServerlibrary, the client need to use ServerProxythe library, but in Python3, both are integrated into a single xmlrpclibrary, respectively xmlrpc.server, and xmlrpc.client.

Second, simple to use

1. The server is implemented

Because it is accessible from the network, and so the web request, we need to identify 供客户端访问的URLand 端口号, and 供客户端调用的服务方法, finally, let our server 一直处于可以被访问的状态.

Example:

from xmlrpc.server import SimpleXMLRPCServer

def setup_socket_server(ip_address='localhost', port=6666):
	"""
    注册一个函数或者类来响应XML-RPC请求,并启动XML-RPC服务器
    :param ip_address: 供客户端连接的IP地址,默认使用localhost,localhost为当前网卡IP,也可以自己指定合法有效的IP地址
    :param port: 供客户端连接的端口号,默认为6666
    :return:
    """
    try:
        service = SimpleXMLRPCServer((ip_address, port))  # 初始化XML-RPC服务
        # 注册一个函数来响应XML-RPC请求,客户端只能调用已注册的函数,比较单一
        service.register_function(function)
        # 注册一个类来响应XML-RPC请求,使用类的好处就是可以把多个方法写到一起,方便管理和调用
        service.register_instance(ServiceMethod())
        service.serve_forever()  # 启动服务器并永久运行
    except Exception as ex:
        raise Exception('Setup socket server error:\n{}'.format(ex))

The above code describes a simple server implementation, the following began to show a complete server configuration
code is as follows:

# -*- coding:utf-8 -*-
import os
import re
from xmlrpc.server import SimpleXMLRPCServer


class ServiceMethod(object):
    """
    这个类包含客户端所有能被执行的方法
    每个方法必须要有一个返回值,如果没有合适的返回值可以直接返回True
    """
    @staticmethod
    def get_server_ip():
        """
        获取服务器端的IP地址
        :return:
        """
        result = os.popen('ipconfig')
        ip_address = re.search(r'IPv4.+?: (\d+?\.\d+?\.\d+?\.\d+)', result .read())
        if ip_address:
            return ip_address.group(1)
        else:
            return 'Server ip address was not found'


def get_server_host_name():
    """
    这是获取服务器端计算机主机名的函数
    :return:
    """
    result = os.popen('ipconfig /all')
    host_name = re.search(r'主机名.+?: (\w+)', result.read())
    if host_name:
        return host_name.group(1)
    else:
        return 'Server host name was not found'


def setup_socket_server(ip_address='localhost', port=6666):
    """
    注册一个函数或者类来响应XML-RPC请求,并启动XML-RPC服务器
    :param ip_address: 供客户端连接的IP地址,默认使用localhost,localhost为当前网卡IP,也可以自己指定合法有效的IP地址
    :param port: 供客户端连接的端口号,默认为6666
    :return:
    """
    try:
        service = SimpleXMLRPCServer((ip_address, port))  # 初始化XML-RPC服务
        print('Server {} Listening on port {} ...'.format(ip_address, port))
        service.register_function(get_server_host_name)  # 注册一个函数
        service.register_instance(ServiceMethod())  # 注册一个类
        service.serve_forever()  # 启动服务器并永久运行
    except Exception as ex:
        raise Exception('Setup socket server error:\n{}'.format(ex))


if __name__ == '__main__':
    setup_socket_server(ip_address='172.31.9.156')

Results of the:

Server 172.31.9.156 Listening on port 6666 ...

I use the machine is automatically assigned an IP address, such as a server-side started well, after the implementation of the Python process does not close, here are two ways to register callable get_server_host_name, ServiceMethod()next to see customers to achieve the end.

2. achieve client

Clients need to configure 服务器端的IP地址and 端口号initialize a server object, and then calls the corresponding method to the server-side.
code show as below:

# -*- coding:utf-8 -*-
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))

    host_name = proxy.get_server_host_name()
    print('Received the server host name: {}'.format(host_name))

    server_ip = proxy.get_server_ip()
    print('Received the server ip: {}'.format(server_ip))


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

Client The results:

Connect to 172.31.9.156:6666 successful ...
Received the server host name: EVALIU
Received the server ip: 172.31.9.156

Successfully connect to the server-side and server-side function returns the print result
See the following server response result:

Server 172.31.9.156 Listening on port 6666 ...
172.31.9.156 - - [15/Jan/2020 10:05:10] "POST / HTTP/1.1" 200 -
172.31.9.156 - - [15/Jan/2020 10:05:10] "POST / HTTP/1.1" 200 -

It can be seen every time the server is accessed access source will print out, I have here is a native client to connect the machine so the server IP address is the same.

Published 27 original articles · won praise 10 · views 387

Guess you like

Origin blog.csdn.net/weixin_43750377/article/details/103978127