Python XML RPC服务器端和客户端实例

yipeiwu_com5年前服务器

一、远程过程调用RPC

XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP as a transport. With it, a client can call methods with parameters on a remote server (the server is named by a URI) and get back structured data. This module supports writing XML-RPC client code; it handles all the details of translating between conformable Python objects and XML on the wire.

简单地,client可以调用server上提供的方法,然后得到执行的结果。类似与webservice。

推荐查看xmlprc的源文件:C:\Python31\Lib\xmlrpc

二、实例

1) Server

复制代码 代码如下:

from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler

def div(x,y):
    return x - y
   
class Math:
    def _listMethods(self):
        # this method must be present for system.listMethods
        # to work
        return ['add', 'pow']
    def _methodHelp(self, method):
        # this method must be present for system.methodHelp
        # to work
        if method == 'add':
            return "add(2,3) => 5"
        elif method == 'pow':
            return "pow(x, y[, z]) => number"
        else:
            # By convention, return empty
            # string if no help is available
            return ""
    def _dispatch(self, method, params):
        if method == 'pow':
            return pow(*params)
        elif method == 'add':
            return params[0] + params[1]
        else:
            raise 'bad method'

server = SimpleXMLRPCServer(("localhost", 8000))
server.register_introspection_functions()
server.register_function(div,"div")
server.register_function(lambda x,y: x*y, 'multiply')
server.register_instance(Math())
server.serve_forever()

2)client

复制代码 代码如下:

import xmlrpc.client

s = xmlrpc.client.ServerProxy('http://localhost:8000')

print(s.system.listMethods())

print(s.pow(2,3))  # Returns 28
print(s.add(2,3))  # Returns 5
print(s.div(3,2))  # Returns 1
print(s.multiply(4,5)) # Returns 20

3)result

相关文章

python 从远程服务器下载东西的代码

复制代码 代码如下:# _*_ coding:utf-8 _*_# name gefile.pyimport osimport statimport socketimport param...

在 Django/Flask 开发服务器上使用 HTTPS

使用 Django 或 Flask 这种框架开发 web app 的时候一般都会用内建服务器开发和调试程序,等程序完成后再移交到生产环境部署。问题是这些内建服务器通常都不支持 HTTPS...

在windows服务器开启php的gd库phpinfo中未发现

在windows服务器开启php的gd库时,使用cgi之后phpinfo()得到的结果中 Configure Command 中并没有出现gd. Configure Command 后显...

python3.8 微信发送服务器监控报警消息代码实现

python3.8 微信发送服务器监控报警消息代码实现

这篇文章主要介绍了python3.8 微信发送服务器监控报警消息代码实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 python版...

python 从远程服务器下载日志文件的程序

复制代码 代码如下:import osimport sysimport ftplibimport socket #####################################...