python rpc講解

來源:互聯網
上載者:User
rpyc (Remote Python Call)為分散式運算環境提供了優良的基礎平台。 使用rpyc編寫c/s結構程式,完全不用考慮老式的socket編程,現在只用編寫簡單的3、5行代碼即可完成以前的數千行代碼的功能。

以簡單一實例講解:

服務端:
[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.

預設是線程模式,線上程模式下rpyc服務會為每個用戶端建立一個線程服務

其它rpyc詳細看官網文檔:http://rpyc.wikidot.com/
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.