服務端:
[python] view plain copy # coding:utf-8 from rpyc import Service from rpyc.utils.serverimport ThreadedServer class TestService(Service): # 對於服務端來說, 只有以"exposed_"打頭的方法才能被用戶端調用,所以要提供給用戶端的方法都得加"exposed_" defexposed_test(self, num): return1+num sr = ThreadedServer(TestRpyc, port=9999, auto_register=False) sr.start()
用戶端:
[python] view plain copy # coding:utf-8 import rpyc # 參數主要是host, port conn =rpyc.connect('localhost',9999) # test是服務端的那個以"exposed_"開頭的方法 cResult =conn.root.test(11) conn.close() 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.