python rpyc 远程调用

来源:互联网 发布:淘宝代理要交钱吗 编辑:程序博客网 时间:2024/05/02 01:42
rpyc (Remote Python Call)为分布式计算环境提供了优良的基础平台。 使用rpyc编写c/s结构程序,完全不用考虑老式的socket编程,现在只用编写简单的3、5行代码即可完成以前的数千行代码的功能。

以简单实例讲解:

服务端:
[python] view plaincopy
  1. # coding:utf-8  
  2.   
  3. from rpyc import Service  
  4. from rpyc.utils.serverimport ThreadedServer  
  5.   
  6. class TestService(Service):  
  7.   
  8.     # 对于服务端来说, 只有以"exposed_"打头的方法才能被客户端调用,所以要提供给客户端的方法都得加"exposed_"  
  9.     defexposed_test(self, num):  
  10.         return1+num  
  11.   
  12. sr = ThreadedServer(TestRpyc, port=9999, auto_register=False)  
  13. sr.start()  

客户端:
[python] view plaincopy
  1. # coding:utf-8  
  2.   
  3. import rpyc  
  4.   
  5. # 参数主要是host, port  
  6. conn =rpyc.connect('localhost',9999)  
  7. # test是服务端的那个以"exposed_"开头的方法  
  8. cResult =conn.root.test(11)  
  9. conn.close()  
  10.   
  11. print cResult  

注:对于返回值cResult
1、如果cResult是数字或字符串的话,那么在conn.close()之后,你可以用cResult的值
2、如果cResult是其它类型的数据的话, 你conn.close()之后,cResult就为空的了(这是因为对于其它类型的返回值,服务端返回的是rpyc.netref的封装nobj, 当访问nobj时,它连接到服务端,取值,并返回给客户端,你close之后就连不到服务端了),所以最好在服务端把计算结果处理下,转换成数字或字符串(对于大字典来说,可以用json转换下,然后客户端再转过来就ok了)

注:classic rpyc服务模式有三种:

Classic Server
The classic server, implemented in rpyc/servers/classic_server.py, is an executable script. When running it, you can specify command line options to control how it behaves:
Option    Description
-m or --mode    One of threaded, forking, or stdio. The default is threaded
-p or --port    The TCP port on which the server listens. Applicable only for threaded and forking modes. The default is 18812
-q or --quiet    Does not display any logs, except for errors. Default is verbose

Modes:

    In the threaded mode, the server creates a thread to serve each client. This is usually the basic setup required. Supported on Windows, Linux, and most other flavors of Unix.
    In the forking mode, the server forks a child process to serve each client. Not supported on Windows.
    The std mode is useful for inetd invocation. In this mode, the server reads from stdin and writes to stdout instead of operating on a socket.

默认是线程模式,在线程模式下rpyc服务会为每个客户端创建一个线程服务

其它rpyc详细看官网文档:http://rpyc.wikidot.com/
0 0