Python Network Programming 简明教程
Python - Remote Procedure Call
远程过程调用 (RPC) 系统使您可以使用与调用本地库中的函数时相同的语法来调用远程服务器上可用的函数。这在两种情况下很有用。
Remote Procedure Call (RPC) system enables you to call a function available on a remote server using the same syntax which is used when calling a function in a local library. This is useful in two situations.
-
You can utilize the processing power from multiple machines using rpc without changing the code for making the call to the programs located in the remote systems.
-
The data needed for the processing is available only in the remote system.
因此,在 Python 中,我们可以将一台机器视为服务器,将另一台机器视为客户端,它将调用服务器来运行远程过程。在我们的示例中,我们将使用 localhost 并将其用作服务器和客户端。
So in python we can treat one machine as a server and another machine as a client which will make a call to the server to run the remote procedure. In our example we will take the localhost and use it as both a server and client.
Running a Server
Python 语言附带一个内置服务器,我们可以将其作为本地服务器运行。用于运行此服务器的脚本位于 python 安装的 bin 文件夹中,并命名为 classic.py。我们可以在 Python 提示符中运行它,并检查它作为本地服务器运行的情况。
The python language comes with an in-built server which we can run as a local server. The script to run this server is located under the bin folder of python installation and named as classic.py. We can run it in the python prompt and check its running as a local server.
python bin/classic.py
当我们运行以上程序时,我们得到以下输出:
When we run the above program, we get the following output −
INFO:SLAVE/18812:server started on [127.0.0.1]:18812
Running a Client
接下来,我们使用 rpyc 模块运行客户端以执行远程过程调用。在下面的示例中,我们在远程服务器中执行 print 函数。
Next we run the client using the rpyc module to execute a remote procedure call. In the below example we execute the print function in the remote server.
import rpyc
conn = rpyc.classic.connect("localhost")
conn.execute("print('Hello from Tutorialspoint')")
当我们运行以上程序时,我们得到以下输出:
When we run the above program, we get the following output −
Hello from Tutorialspoint
Expression Evaluation through RPC
使用上述代码示例,我们可以通过 rpc 使用 Python 的内置函数进行表达式执行和求值。
Using the above code examples we can use python’s in-built functions for execution and evaluation of expressions through rpc.
import rpyc
conn = rpyc.classic.connect("localhost")
conn.execute('import math')
conn.eval('2*math.pi')
当我们运行以上程序时,我们得到以下输出:
When we run the above program, we get the following output −
6.283185307179586