How to do it...

In this example, we'll see how to build and use a simple client-server communication using the Pyro4 middleware. The code for the client is pyro_server.py:

  1. Import the Pyro4 library:
import Pyro4
  1. Define the Server class that contains the welcomeMessage() method that will be exposed:
class Server(object):
@Pyro4.expose
def welcomeMessage(self, name):
return ("Hi welcome " + str (name))
Note that the decorator, @Pyro4.expose, means that the preceding method will be remotely accessible.
  1. The startServer function contains all the instructions that are used to start the server:
def startServer():
  1. Next, build the server instance of the Server class:
server = Server()
  1. Then, define the Pyro4 daemon: 
daemon = Pyro4.Daemon()
  1. To execute this script, we must run a Pyro4 statement to locate a nameserver:
ns = Pyro4.locateNS()
  1. Register the object server as Pyro object; it will only be known inside the Pyro daemon:
uri = daemon.register(server)
  1. Now, we can register the object server with a name in the nameserver:
ns.register("server", uri)
  1. The function ends with a call to the daemon's requestLoop method. This starts the event loop of the server and waits for calls:
print("Ready. Object uri =", uri)
daemon.requestLoop()
  1. Finally, call startServer via the main program:
if __name__ == "__main__":
startServer()

Here is the code for the client (pyro_client.py):

  1. Import the Pyro4 library:
import Pyro4
  1. The Pyro4 API enables the developer to distribute objects in a transparent way. In this example, the client script sends requests to the server program in order to execute the welcomeMessage() method:
uri = input("What is the Pyro uri of the greeting object? ").strip()
name = input("What is your name? ").strip()
  1. Then, the remote call is created: 
server = Pyro4.Proxy("PYRONAME:server")
  1. Finally, the client calls the server, printing a message:
print(server.welcomeMessage(name))
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.162.87