Python Network Programming Remote Procedure Call
Python Network Programming: Remote Procedure Calls
The Remote Procedure Call (RPC) system allows you to call functions on a remote server using the same syntax as you would for functions in a local library. This is useful in two situations.
- You can use RPC to leverage the processing power of multiple machines without having to change the code that calls the program on the remote system.
- The data required for the processing is only available on the remote system.
Thus, in Python, we can treat one machine as a server and another as a client, which calls the server to run the remote program. In our example, we will use localhost as both the server and the client.
Running a Server
The Python language has a built-in server that we can run as a local server. The script that runs this server is located in the bin folder of your Python installation and is named classic.py. We can run it from a Python prompt and check that it works 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
Next, we use the rpyc module to run a client and perform remote procedure calls. In the following example, we execute the print function on 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 via RPC
Using the above code example, we can use Python’s built-in functions to execute and evaluate expressions via 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